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
This is optimized Flem's solution:
In the newer version of .net such as .net standard,
type.IsValueType
needs to be written astype.GetTypeInfo().IsValueType
Why not call the method that returns default(T) with reflection ? You can use GetDefault of any type with:
The Expressions can help here:
I did not test this snippet, but i think it should produce "typed" nulls for reference types..
I do the same task like this.
If you're using .NET 4.0 or above and you want a programmatic version that isn't a codification of rules defined outside of code, you can create an
Expression
, compile and run it on-the-fly.The following extension method will take a
Type
and get the value returned fromdefault(T)
through theDefault
method on theExpression
class:You should also cache the above value based on the
Type
, but be aware if you're calling this for a large number ofType
instances, and don't use it constantly, the memory consumed by the cache might outweigh the benefits.