sma*_*man 9 c# reflection struct default default-constructor
如果我有一个值类型的泛型类型参数,我想知道一个值是否等于默认值我测试它像这样:
static bool IsDefault<T>(T value){
where T: struct
return value.Equals(default(T));
}
Run Code Online (Sandbox Code Playgroud)
如果我没有泛型类型参数,那么我似乎必须使用反射.如果该方法必须适用于所有值类型,那么执行此测试的方法是否比我在此处所做的更好?:
static bool IsDefault(object value){
if(!(value is ValueType)){
throw new ArgumentException("Precondition failed: Must be a ValueType", "value");
}
var @default = Activator.CreateInstance(value.GetType());
return value.Equals(@default);
}
Run Code Online (Sandbox Code Playgroud)
另外,在评估Nullable结构方面,我有什么不考虑的吗?
我发现以下扩展方法很有用,适用于所有类型:
public static object GetDefault(this Type t)
{
return t.IsValueType ? Activator.CreateInstance(t) : null;
}
public static T GetDefault<T>()
{
var t = typeof(T);
return (T) GetDefault(t);
}
public static bool IsDefault<T>(T other)
{
T defaultValue = GetDefault<T>();
if (other == null) return defaultValue == null;
return other.Equals(defaultValue);
}
Run Code Online (Sandbox Code Playgroud)
老问题,但接受的答案对我不起作用,所以我提交这个(可能可以做得更好):
public static object GetDefault(this Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var valueProperty = type.GetProperty("Value");
type = valueProperty.PropertyType;
}
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
typeof(int).GetDefault(); // returns 0
typeof(int?).GetDefault(); // returns 0
typeof(DateTime).GetDefault(); // returns 01/01/0001 00:00:00
typeof(DateTime?).GetDefault(); // returns 01/01/0001 00:00:00
typeof(string).GetDefault(); // returns null
typeof(Exception).GetDefault(); // returns null
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5475 次 |
| 最近记录: |