如何为可空类型获取字符串类型

ryu*_*ice 4 c# reflection

我正在使用从我的dbml文件生成的数据类的属性生成T4模板.要获取我使用的类的属性类型item.PropertyType.Name,问题是,对于可空类型,它返回Nullable``1 , is there a way to getNullable for example, orint?`?

Dar*_*opp 11

int?=== Nullable<int>.他们是一样的.如果你想知道nullable是什么类型,那么你可以使用Nullable.GetUnderlyingType(typeof(int?))方法来获取类型(在这个例子中int)

Nullable.GetUnderlyingType


Jos*_*osh 7

GetGenericArguments是您想要的方法.

if (item.PropertyType.IsGenericType) {
    if (item.PropertyType.GetGenericType() == typeof(Nullable<>)) {
        var valueType = item.PropertyType.GetGenericArguments()[0];
    }
}
Run Code Online (Sandbox Code Playgroud)

尽管如此,在这种情况下,Darren的答案要简单得多,因为当你传入一个不可为空的类型时它会返回null.