C# Perversion: Generic Constructors using Reflection
This MIGHT be useful in the future, but right now I was getting my hands dirty with some reflection code and it intrigued me: generic constructors.
This code will indirectly invoke any publicly exposed constructor of AnyClass
public AnyType DefaultConstructor<AnyType>()
{
return ExtensibleConstructor<AnyType>(new Type[] {}, new object[] {});
}
public AnyType ExtensibleConstructor<AnyType>(Type[] argTypes, object[] args)
{
Debug.Assert(argTypes.Length == args.Length, "Constructor argument lengths must match");
Type theType = typeof (AnyType);
ConstructorInfo theConstructor =
theType.GetConstructor(argTypes);
Debug.Assert(theConstructor != null,
"This type of class [" + theType + "] doesnt have a matching constructor signature");
return (AnyType) theConstructor.Invoke(args);
}
This code will indirectly invoke any publicly exposed constructor of AnyClass
I understand the reflection concept, but I am one of those guys that uses it as a last resort, not because of the performance risk, but because I fear it can obfuscate the code.
public void Test()
{
StringBuilder _stringBuilder = DefaultConstructor<StringBuilder>();
_stringBuilder = ExtensibleConstructor<StringBuilder>(new Type[] {typeof (string)}, new object[] {""});
}
Labels: C#


0 Comments:
Post a Comment
<< Home