简体   繁体   中英

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?

You can use IsInstaceOfType method and is to check the type.

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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