Skip to main content
 首页 » 编程设计

c#之如何比较 C# 中的 2 个相似类型

2024年02月05日15jirigala

我想问一下我们如何在 C# 中比较两种类型。

我的场景是:

Nullable<int> Rating; 
int NeedCompareType; 

每次我比较这两个时,它都会返回错误的结果。 在这种情况下无论如何我都会返回 true 因为 int两行都有类型。

我的比较线是:

if(Rating.GetType() == NeedCompareType.GetType()) 

编辑: 实际上这是我的程序代码:

    public object this[string propertyName] 
    { 
        get 
        { 
            PropertyInfo property = GetType().GetProperty(propertyName); 
            return property.GetValue(this, null); 
        } 
        set 
        { 
            PropertyInfo property = GetType().GetProperty(propertyName); 
            IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true); 
            if (property.PropertyType == typeof(System.DateTime)) 
            { 
                property.SetValue(this, Convert.ToDateTime(value, culture), null); 
            } 
            else if (property.PropertyType == typeof(int)) 
            { 
                property.SetValue(this, Int32.Parse((string)value)); 
            } 
            else 
            { 
                property.SetValue(this, value, null); 
            } 
 
        } 
    } 

此代码的目的是将 Controller 从浏览器接收的值转换为字符串类型,然后我想将字符串类型转换为适当的类型 unknown yet模型的属性(在本例中为 public Nullable<int> Rating { get; set; } )。

如你所知,我想要 propertyName = "Rating" ,它应该执行第二个 if 语句,但它不会,因为 typeof(int)和 typeof(Nullable<int>)会有所不同。

抱歉我的英语不好

请您参考如下方法:

实际上,这一行:

if(Rating.GetType() == NeedCompareType.GetType()) 

总是要么进入条件,要么抛出 NullReferenceException - 因为 Rating.GetType()遗嘱盒Rating到盒装 Int32或空引用。

现在如果你说你想比较typeof(int)和 typeof(Nullable<int>)你可以使用:

public bool SomewhatEqual(Type t1, Type t2) 
{ 
    return t1 == t2 || 
           t1 == Nullable.GetUnderlyingType(t2) || 
           Nullable.GetUnderlyingType(t1) == t2; 
} 

现在我们已经看到了您真正感兴趣的代码,听起来您只想将每个具有可空类型的属性视为不可空类型。这很简单:

set 
{ 
    PropertyInfo property = GetType().GetProperty(propertyName); 
    Type type = property.GetType(); 
    // Treat nullable types as their underlying types. 
    type = Nullable.GetUnderlyingType(type) ?? type; 
    // TODO: Move this to a static readonly field. No need to 
    // create a new one each time 
    IFormatProvider culture = new CultureInfo("fr-FR", true); 
    if (type == typeof(System.DateTime)) 
    { 
        property.SetValue(this, Convert.ToDateTime(value, culture), null); 
    } 
    else if (type == typeof(int)) 
    { 
        property.SetValue(this, Int32.Parse((string)value)); 
    } 
    else 
    { 
        property.SetValue(this, value, null); 
    } 
}