简体   繁体   中英

C# cast object type

How can I cast object type to different type?

public T Get<T>(T t)
{
    if (t is TypeA)
    {
        TypeA a = (TypeA)t; //error
    }
}

试试这样:

TypeA a = (TypeA)(object)t;

One way would be to use as

public T Get<T>(T t)
{
    if(t is TypeA) {
        TypeA a = t as TypeA;
    }
}

The other would be to use Convert

public T Get<T>(T t)
{
    if(t is TypeA) {
        TypeA a = (TypeA) Convert.ChangeType(t, typeof(TypeA));
    }
}

https://dotnetfiddle.net/7tb2Fl

I couldn't get an error here. It will cast fine

using System;

public class Program
{
    public class TypeA
    {
        public int Id;
    }

    public class TypeB : TypeA
    {
        public int name;
    }

    public static void Main()
    {
        var t = new TypeB{Id = 1, name = 15};
        if (t is TypeA)
        {
            TypeA a = (TypeA)t;// no error
            Console.WriteLine(a.Id); // no error
        }
    }
}

//Just thought of it and not tested:

public T ConvertType<T>(Object obj)
{
    if (obj is T)
        return (T)Convert.ChangeType(obj, typeof(T));
    return default(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