c# - 将数值具体类型转换为数值泛型

标签 c# generics

我想知道是否存在允许转换在以下情况下工作的数值类型的特定约束:

class MyClass<T>
{

...

void MyMethod()
{
    ....
    byte value = AnotherObject.GetValue()

    Tvalue = (T)value;
    ....
}

...

}

我试过像这样装箱和拆箱:

Tvalue = (T)(object)value;

但这仅在 T == byte 时有效。否则我会得到一个 InvalidCastException

T 始终是数字类型(如短整型、浮点型等)。

最佳答案

是的,您只能将值拆箱为相同类型。

你用过吗

Tvalue = (T) Convert.ChangeType(value, typeof(T));

?这是一个示例:

using System;

class Test
{
    static void Main()
    {
        TestChange<int>();
        TestChange<float>();
        TestChange<decimal>();
    }

    static void TestChange<T>()
    {
        byte b = 10;
        T t = (T) Convert.ChangeType(b, typeof(T));
        Console.WriteLine("10 as a {0}: {1}", typeof(T), t);
    }
}

这里没有限制,虽然你可以指定

where T : struct, IComparable<T>

作为第一关。不过,该约束与转换工作无关 - 它只是试图阻止调用者使用不合适的类型。

关于c# - 将数值具体类型转换为数值泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661366/

相关文章:

java - 与原始类型相比,了解方法上的泛型

java - 静态泛型方法,类型推断导致 java.lang.VerifyError : Verifier rejected class

c# - 更新自动计算的属性的绑定(bind)

c# - 在 XAML 中将数据绑定(bind)到 TreeView

c# - 为什么这个例子中的队列锁是必要的

swift - Swift 中的通用类型作为返回值

generics - 如何根据其父类检查类型?

java - jsf 转换器 : How to find out the class type of the actual passed value String?

c# - 获取xml文档中元素数量的快速方法

c# - 将 Gtk# 对话框放置在 Gtk 窗口的中心