简体   繁体   English

如何为以下情况创建泛型类型实例

[英]How to create a generic type instance for the following situation

i have the following code, please let me know how to create the instance at runtime without specifying the type while coding. 我有以下代码,请让我知道如何在运行时创建实例,而无需在编码时指定类型。

MyObject productobject = something.

i need the object of type 我需要类型的对象

 AccessValuesFrom<long,double>,AccessValuesFrom<long,string>..etc

Generally i can create the object is below: 一般我可以创建对象如下:

 AccessValuesFrom<long,double> accessData=productobject.ElementInfo.GetAccessValues<double>(something, something);

but i need the AccessValuesFrom at run time. 但我在运行时需要AccessValuesFrom。 long is pre-defined. long是预先定义的。 how to create the instances for such type when there is no direct way of creating the instance(my situation i have to call 当没有直接创建实例的方法时,如何为这种类型创建实例(我的情况我必须调用

  productobject.ElementInfo.GetAccessValues<double>(something, something)

to create the instace. 创造实例。

If you have a Type object at this point, you can implement GetAccessValues like this: 如果此时有一个Type对象,可以像这样实现GetAccessValues

object GetAccessValues(Type type, something, something)
{
     var result = Activator.CreateInstance(
           typeof(AccessValuesFrom<,>).MakeGenericType(typeof(long), type));
     //do something with something
     return result;
}

also it'll be good to create an interface for all generic AccessValuesFrom with common methods in it. 也可以使用常用方法为所有通用AccessValuesFrom创建一个接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM