简体   繁体   English

检查对象等于泛型类型

[英]Check object is equal to generic type

I have a method that does some type conversion. 我有一个方法可以进行一些类型转换。 I don't want to go through the whole process if the type is equal to the generic types passed. 如果类型等于传递的泛型类型,我不想完成整个过程。 Here's a snippet. 这是一个片段。

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

I'm checking is the object @this is already of type T which seems to work, but is this the best way of doing this? 我正在检查对象@this已经是T类似乎可以工作,但这是最好的方法吗?

You can use IsInstaceOfType method and is to check the type. 您可以使用IsInstaceOfType方法is检查的类型。

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

This might also work 这也可能有用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM