与铸造的GetType() [英] Cast with GetType()

查看:90
本文介绍了与铸造的GetType()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能投的对象从的GetType返回类型()?我想,可以接受一个对象(匿名类型),但再回到转换为匿名类型对象的一般方法。我一直在想用LCG DynamicMethod的建立在一个容器类中的方法,但我不能确切地弄清楚,是什么样子。投用的GetType()方法的想法是能够得到匿名类型和对象转换到它的实际类型实际上不知道的类型。

Is it possible to cast an object to the type returned from GetType()? I'd like a generic method that can accept an object (for anonymous types) but then return an object cast as the anonymous type. I've been thinking of using the LCG DynamicMethod to build a method on a container class, but I can't exactly figure out what that would look like. The idea to cast with the GetType() method was to be able to get the anonymous type and cast an object to its actual type without actually knowing the type.

的总体目标是要坚持匿名类型对象放入容器,我可以然后共享和方法之间传递。

The overarching goal is to stick anonymous-typed objects into a container, that I could then share and pass between methods.

推荐答案

您的意图非常明确;然而,一种选择是泛型和 MakeGenericMethod 尤其如此。你要什么与此有关呢?例如:

Your intent is very unclear; however, one option is generics and MakeGenericMethod in particular. What do you want to do with this? For example:

static class Program
{
    static void Main()
    {
        object obj = 123.45;
        typeof(Program).GetMethod("DoSomething")
            .MakeGenericMethod(obj.GetType())
            .Invoke(null, new object[] { obj });
    }
    public static void DoSomething<T>(T value)
    {
        T item = value; // well... now what?
    }    
}



所以,现在我们有值,类型为双击 - 但仍有不多,我们可以用它做除了调用的其他的泛型方法......那是什么,你想做的事在这里?

So now we have the value, typed as double via generics - but there still isn't much we can do with it except for calling other generic methods... what was it you want to do here?

这篇关于与铸造的GetType()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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