指示一个通用返回动态类型的对象 [英] Instructing a generic to return an object of a dynamic type

查看:114
本文介绍了指示一个通用返回动态类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是形式的后续行动,我原来的问题的这里

This question is sort of a follow-up to my original question here.

让我们说,我有以下的通用类(!简化了^ _ ^):

Let's say that I have the following generic class (simplifying! ^_^):

class CasterClass<T> where T : class
{
    public CasterClass() { /* none */ }
    public T Cast(object obj)
    {
        return (obj as T);
    }
}

这也在对象转换成指定类型的能力。

Which has the ability to cast an object into a specified type.

不幸的是,在编译时,我不用知道到底是什么类型的我会和上班的奢侈,因此我不得不通过反射来实例化这个类,像这样:

Unfortunately, at compile-time, I don't have the luxury of knowing what types exactly I'll have to work with, so I'll have to instantiate this class via reflection, like so:

Type t = typeof(castedObject);

// creating the reflected Caster object
object CasterObj = Activator.CreateInstance(
    typeof(CasterClass<>).MakeGenericType(t)
);

// creating a reflection of the CasterClass' Cast method
MethodInfo mi = typeof(CasterClass<>).GetMethod("Cast");

但问题是,有一次我打电话使用mi.Invoke()的方法,它会返回(由于反射)的类型的对象输出,而不是专门类型的牛逼实例。

Problem is, once I call the method using mi.Invoke(), it will return an object typed output, instead of the specifically-typed T instance (because of reflection).

有没有办法让通过反射调用的方法返回一个动态类型,如上图所示?我是pretty的肯定.NET 3.5没有设施,以铸造成一个动态类型(或者更确切地说,这将是非常不切实际的)。

Is there any way to have a method invoked through reflection return a dynamic type, as illustrated above? I'm pretty sure that .NET 3.5 doesn't have the facilities to cast into a dynamic type (or rather, it would be very impractical).

非常感谢!

推荐答案

如果你有超过你将要使用的类控制,让他们所有的实例包含你会被调用方法的接口,一旦你实例,转换为界面。

If you have control over the classes you'll be working with, have them all instantiate an interface that contains the methods you'll be calling and once you instantiate, cast to the interface.

我也贴一个答案,你的$ P $用同样的想法pvious的问题。

I also posted an answer to your previous question with the same idea.

这篇关于指示一个通用返回动态类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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