装箱值类型的通用拆箱 [英] Generic unboxing of boxed value types

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

问题描述

我有被限制在结构体的通用功能。我输入盒装(物)。是否可以拆箱在运行时的值,以避免检查每一个可能的类型和手工做类型转换?

I have a generic function that is constrained to struct. My inputs are boxed ("objects"). Is it possible to unbox the value at runtime to avoid having to check for each possible type and do the casts manually?

请参阅上面的例子:

   public struct MyStruct
    {
        public int Value;
    }

    public void Foo<T>(T test)
        where T : struct
    {
        // do stuff
    }

    public void TestFunc()
    {
        object o = new MyStruct() { Value = 100 }; // o is always a value type

        Foo(o);
    }

在这个例子中,我知道,O必须要在结构(然而,它并不需要是MYSTRUCT ...)。有没有一种方法叫富而不万吨样板code,检查每一个可能的结构类型?

In the example, I know that o must be a struct (however, it does not need to be MyStruct ...). Is there a way to call Foo without tons of boilerplate code to check for every possible struct type?

感谢你。

推荐答案

.NET泛型的方式,允许值类型为泛型类型参数,而不会产生任何装箱/拆箱的开销来实现。由于需要的资料铸造对象调用foo之前,你不利用这一点,其实你甚至不接受仿制药的优势可言。

.NET Generics are implemented in a manner that allows value types as a generic type parameter without incurring any boxing/unboxing overhead. Because your're casting to object before calling Foo you don't take advantage of that, in fact you're not even taking advantage of generics at all.

使用泛型摆在首位的整点是要取代对象 - 成语。我想你错过了这个概念在这里。 无论何种类型 T 恰好是,它是在运行时间,因为你的约束到结构保证是一个结构类型。

The whole point of using generics in the first place is to replace the "object-idiom". I think you're missing the concept here. Whatever type T happens to be, it is available at run-time and because you constrained it to struct guaranteed to be a struct type.

您TestFunc可以这样写没有问题:

Your TestFunc could be written like this without problem:

public void TestFunc()
{
    MyStruct o = new MyStruct() { Value = 100 }; // o is always a value type

    Foo<MyStruct>(o);
}

看着富,它看起来像这样在您的示例:

Looking at Foo, it would look like this in your example:

public void Foo<T>(T test)
    where T : struct
{
    T copy = test; // T == MyStruct
}

编辑:

好了,因为OP澄清他想要的东西来调用泛型方法,但不知道他的结构类型(它只是反对)。打电话给你的通用方法,用正确的类型参数的最简单方法是使用一个小的反射。

Ok, since the OP clarified what he wants to call the generic method but doesn't know the type of his struct (it's just object). The easiest way to call your generic method with the correct type parameter is to use a little reflection.

public void TestFunc()
{
    object o = new DateTime();

    MethodInfo method = this.GetType().GetMethod("Foo");
    MethodInfo generic = method.MakeGenericMethod(o.GetType());
    generic.Invoke(this, new object[] {o});


}
public void Foo<T>(T test)
    where T : struct
{
    T copy = test; // T == DateTime
}

这篇关于装箱值类型的通用拆箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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