【问题标题】:How to Cast System.ValueType to Generic Type (T) in C#?如何在 C# 中将 System.ValueType 转换为泛型类型 (T)?
【发布时间】:2019-11-25 06:34:46
【问题描述】:

我有一个 C# 代码片段,错误如下:

无法将 System.ValueType 转换为 T

请指导我解决这个问题

这是一个代码

public static T Add<T>(this Enum type, T value)
{
    try
    {
        return (T) (ValueType) (Convert.ToInt32(type) | (int) (object) value);
    }
    catch (Exception ex)
    {
        throw new ArgumentException(string.Format("Could not append value from enumerated type '{0}'.", (object) typeof (T).Name), ex);
    }
}

现在我该如何运行这个错误?

【问题讨论】:

  • @Jazb 不幸的是没有。 thic 代码在 32 位版本中真正运行。当我们反编译它并以64位重新编译时,出现了这个错误
  • 从一开始就分享它会很有用......

标签: c# asp.net enums typeconverter generic-type-argument


【解决方案1】:

你可以使用Convert.ChangeType

例如,

var result = (ValueType) (Convert.ToInt32(type) | (int) (object) value);
return (T)Convert.ChangeType(result,typeof(T));

【讨论】:

    【解决方案2】:

    编译器不知道T 可以从ValueType 向上转换,因为它不知道T 是一个值类型。您需要为此添加 struct 约束。

    public static T Add<T>(this Enum type, T value) where T : struct
    

    现在,转换为 ValueType 的中间转换等效于转换为 object 并且可以编译。

    然而,如果T 不是intint?,则此转换将失败并显示InvalidCastException(它甚至不能是带有@ 的int? 987654333@ 约束)。这是因为在 int 上执行 (T)(object) 首先将整数装箱,然后尝试将其拆箱。而装箱的int 只能拆箱为intint?(对于任何值类型都是如此,您只能将值类型T 拆箱为TT? 类型的变量) .所以这个泛型代码几乎没用,因为它只适用于一种类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多