获取的实际类型的通用对象参数 [英] Get the actual type of a generic object parameter

查看:80
本文介绍了获取的实际类型的通用对象参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题毫无疑问元素已经被问过,但我无法找到答案。 (免责声明:这是相关的,但是从最近的问题我问分开)

No doubt elements of this question have been asked before, but I'm having trouble finding an answer. (Disclaimer: this is related, but separate from a recent question I asked).

我有这样一个方法:

public static void Method<T>(MethodInfo m, T value)
{
  Type memberType = m.GetValueType();

  if (memberType.IsAssignableFrom(typeof(List<T>))
  {
    object memberValue = Activator.CreateInstance(memberType);
    ((List<T>)memberValue).Add(value);
  }
}

这当我这样称呼它正常工作:

This works fine when I call it like this:

string s = "blah";
Method(memberInfo, s);

不过,我需要调用的范型这个方法,所以我称它像这样的:

However, I need to call this method using a generic type, so I'm calling it like this:

Type valueType = someType;
object passValue = someMethod.MakeGenericMethod(new Type[] { valueType }).Invoke(this, new object[] { });
/* Call my original method */
Method(memberInfo, passValue );

现在,智能感知知道在方法和LT的价值; T>是任何类型的值类型是(说FooObject'),但'T'是对象,这意味着。一个List< FooObject>是的的从分配列表< T>(即一个List<对象>)

Now, intellisense knows that 'value' in Method<T> is whatever type valueType is (say 'FooObject'). But 'T' is object, which means that a List<FooObject> is not assignable from a List<T> (i.e. a List<object>).

我使用尝试。 Convert.ChangeType的变量(passValue')事先但又没更加有用。

I've tried using Convert.ChangeType on the variable ('passValue') beforehand but that wasn't any more useful.

由于没有办法给一个变量转换为一个类型类型变量,我该如何解决这个问题?

As there is no way to cast a variable to the Type of a type variable, how do I get around this?

时以某种方式不依赖于IsAssignableFrom做的是否会工作的一个松散型检查的最佳解决方案?这里的问题是,我不知道我能正确地投了memberValue除非'T'是真正memberValue的元素类型。

Is the best solution to somehow not rely on IsAssignableFrom and do a looser type check of whether this will work? The problem with this is that I'm not sure I'll be able to cast the memberValue properly unless 'T' is truly the element type of memberValue.

推荐答案

您很幸运。我其实不得不做一些非常相似的一个几个星期前。

You're in luck. I actually had to do something very similar a few weeks ago.

有关详细说明见上面的博客文章,但基本上总体思路是,以反映类型和手动精确设置的参数调用该方法。

For a detailed explanation see the above blog post, but basically the general idea is to reflect the type and manually invoke the method with an explicit set of parameters.

typeof(MyClass).GetMethod("Foo").MakeGenericMethod(new[] { param.GetType() }).Invoke(null, new[] { param });



这不是<击>非常类型安全的,但它确实你到底是什么寻找。

It's not very type safe, but it does exactly what you're looking for.

class Program
{

    static void Main(string[] args)
    {
        object str = "Hello World";
        object num = 5;
        object obj = new object();

        Console.WriteLine("var\tvalue\t\tFoo() Type\tCallFoo() Type");
        Console.WriteLine("-------------------------------------------------------");
        Console.WriteLine("{0}\t{1}\t{2}\t{3}", "str", str, MyClass.Foo(str), MyClass.CallFoo(str));
        Console.WriteLine("{0}\t{1}\t\t{2}\t{3}", "num", num, MyClass.Foo(num), MyClass.CallFoo(num));
        Console.WriteLine("{0}\t{1}\t{2}\t{3}", "obj", obj, MyClass.Foo(obj), MyClass.CallFoo(obj));
    }

}

class MyClass
{
    public static Type Foo<T>(T param)
    {
        return typeof(T);
    }

    public static Type CallFoo(object param)
    {
        return (Type)typeof(MyClass).GetMethod("Foo").MakeGenericMethod(new[] { param.GetType() }).Invoke(null, new[] { param });
    }

}



输出

   var     value           Foo() Type      CallFoo() Type
   -------------------------------------------------------
   str     Hello World     System.Object   System.String
   num     5               System.Object   System.Int32
   obj     System.Object   System.Object   System.Object

这篇关于获取的实际类型的通用对象参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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