如何为以下情况创建一个泛型类型实例 [英] How to create a generic type instance for the following situation

查看:98
本文介绍了如何为以下情况创建一个泛型类型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,请让我知道如何在运行时创建实例,而不必在编码时指定类型。

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.

我需要

 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);

但我需要运行时的AccessValuesFrom。长是预定义的。如果没有直接创建实例的方式,那么如何为这种类型创建实例(我的情况是我必须调用

but i need the AccessValuesFrom at run time. long is pre-defined. 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)

来创建instace。

to create the instace.

推荐答案

如果您此时有 Type 对象,则可以实现 GetAccessValues 像这样:

If you have a Type object at this point, you can implement GetAccessValues like this:

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

也可以创建一个接口所有通用的 AccessValuesFrom 及其中的常用方法。

also it'll be good to create an interface for all generic AccessValuesFrom with common methods in it.

这篇关于如何为以下情况创建一个泛型类型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆