【问题标题】:Check object is equal to generic type检查对象是否等于泛型
【发布时间】:2012-11-08 10:15:23
【问题描述】:

我有一个方法可以进行一些类型转换。如果类型等于传递的泛型类型,我不想经历整个过程。这是一个sn-p。

    public static T ConvertTo<T>(this object @this)
    {
        if (typeof(T) == @this.GetType())
            return (T)@this;
    }

我正在检查对象 @this 是否已经是 T 类型,这似乎可以工作,但这是最好的方法吗?

【问题讨论】:

  • 有什么理由要使用 exact 类型而不是 is?
  • 没有 Jon,但作为一个 'dotnetnoob' 我可以让 'is' 语法为我工作。
  • 另一件要检查的事情:你需要它来为值类型和引用类型工作吗?如果没有,where T : class 约束可能会让生活更简单。
  • 它需要适用于 int (+ 其他数字变量) + bool/guid/string

标签: c# .net typeof gettype generic-type-argument


【解决方案1】:

您可以使用IsInstaceOfType 方法和is 来检查类型。

public static T ConvertTo<T>(this object @this)
{
    if (@this is T)
       return (T)@this;
    else
       return default(T);
}

【讨论】:

  • 为什么不直接说@this is T 而不是typeof(T).IsInstanceOfType(@this)
  • 肯定有其他问题。 @this is T 是一个完全有效的表达式。 (我只是对其进行了测试以确保我没有吸烟)。
【解决方案2】:

这也可能有效

public static T ConvertTo<T>(this object @this)
{
    return (T)System.Convert.ChangeType(@this, typeof(T));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 2021-02-06
    • 2016-01-14
    相关资源
    最近更新 更多