Im trying to accomplish something which may seem a bit convoluted but would be quite helpful in my situation, looks something like this.
public class CommonBaseClass {}
public class Type1Object : CommonBaseClass {}
public class Type2Object : CommonBaseClass {}
public class Type3Object : CommonBaseClass {}
public static Dictionary<string, Type> DataTypes = new Dictionary<string, Type>()
{
{ "type1" , typeof(Type1Object) },
{ "type2" , typeof(Type2Object) },
{ "type3" , typeof(Type3Object) }
};
public static CommonBaseClass GetGenericObject(string type)
{
return new DataTypes[type](); //How to instantiate generic class?
}
Because I can guarantee that all the constructors have the same signature I know this will work, just not sure how to let the compiler know.
Thanks in advance
I don't see any generics in here really, but it looks like you want:
return (CommonBaseClass) Activator.CreateInstance(DataTypes[type]);
If you need to use parameterized constructors, use an alternative overload of Activator.CreateInstance
.
Alternatively, consider changing your dictionary to be of delegates:
private static Dictionary<string, Func<CommonBaseClass>> DataTypes =
new Dictionary<string, Func<CommonBaseClass>>
{
{ "type1", () => new Type1Object() }
{ "type2", () => new Type2Object() },
{ "type3", () => new Type3Object() }
};
public static CommonBaseClass GetGenericObject(string type)
{
return DataTypes[type]();
}
Try this:
public class Foo
{
public static CommonBaseClass GetGenericObject<T>() where T : CommonBaseClass
{
return (CommonBaseClass)Activator.CreateInstance<T>();
}
public void Test()
{
CommonBaseClass b = GetGenericObject<Type1Object>();
}
}
Using generics can solve this problem a lot better than having a dictionary of type mapping.
A small test application:
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var dataTypes = new Dictionary<string, Type>
{
{"type1", typeof (Type1Object)},
{"type2", typeof (Type2Object)},
{"type3", typeof (Type3Object)}
};
Func<string, CommonBaseClass> GetGenericObject = t =>
{
return (CommonBaseClass)Activator.CreateInstance(dataTypes[t]);
};
var myGenericObject = GetGenericObject("type1");
}
}
public class CommonBaseClass { }
public class Type1Object : CommonBaseClass { }
public class Type2Object : CommonBaseClass { }
public class Type3Object : CommonBaseClass { }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.