生成泛型类型在运行时 [英] Generate Generic Type At Runtime

查看:117
本文介绍了生成泛型类型在运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用一个变量的类型设置为其他普通变量的类型?

I am wondering if it is possible to use the type of one variable to set as the type of another generic variable?

例如,说我有这样的代码

For example, say I have this code:

public class Foo: IBar<ushort>
{
    public FooBar()
    {
        Value = 0;
    }

    public ushort Value { get; private set; }
}



我也有这个类:

I also have this class:

public class FooDTO<TType> : IBar<TType>
{
    public TType Value { get; private set; }
}

在这些实施例中,在用于IBAR的接口有属性

In these examples, in the interface for IBar has the property

TType Value;



然后在我的代码,我有这个

Then in my code I have this

var myFoo = new Foo();
var fooDataType = myFoo.Value.GetType();

//I know this line of code does not compile, but this is what I am looking to be able to do
var myFooDTO= new FooDTO<fooDataType>();



就是我在寻找可能的吗? 。难道是高使用代码太慢(因为使用反射

Is what I am looking for possible? Would it be too slow for high use code (because of using reflection.

推荐答案

为什么不使用方法类型推断:

Why not use Method type inference:

public class FooDTO<TType> {
    public TType Value { get; private set; }
}

public class Foo : FooDTO<ushort> { }

static FooDTO<T> GetTypedFoo<T>(T Obj) {
    return new FooDTO<T>();
}

static void Main(string[] args) {
   Foo F = new Foo();

   var fooDTO = GetTypedFoo(F.Value);
}

这篇关于生成泛型类型在运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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