I'm using reflection to loop through a Type
's properties and set certain types to their default. Now, I could do a switch on the type and set the default(Type)
explicitly, but I'd rather do it in one line. Is there a programmatic equivalent of default?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
You can use
PropertyInfo.SetValue(obj, null)
. If called on a value type it will give you the default. This behavior is documented in .NET 4.0 and in .NET 4.5.The chosen answer is a good answer, but be careful with the object returned.
Extrapolating...
Equivalent to Dror's answer but as an extension method:
Can't find anything simple and elegant just yet, but I have one idea: If you know the type of the property you wish to set, you can write your own
default(T)
. There are two cases -T
is a value type, andT
is a reference type. You can see this by checkingT.IsValueType
. IfT
is a reference type, then you can simply set it tonull
. IfT
is a value type, then it will have a default parameterless constructor that you can call to get a "blank" value.Why do you say generics are out of the picture?