将<t>转换为List

时间:2016-08-05 08:14:05

标签: c# generics

我有一个接受Generic Type的方法。我想把它投到List。我用以下示例尝试了它。我是Generics的新手。我正在尝试。

    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.Name = "a";
            emp.Id = 1;
            List<Employee> empList = new List<Employee>();
            empList.Add(emp);
            get(emp);
            get(empList);
        }

        public static void get<T>(T targetObj)
        {
            if (targetObj.GetType().IsGenericType)
            {
                 Base baseDo = targetObj as Base;//Getting null
                 List<Base> baseList = targetObj as List<Base>;//Getting null
            }
            else
            {
                Base p = targetObj as Base;
            }
        }
    }
    public class Base
    {
        public long Id { get; set; }
    }
    public class Employee : Base
    {
        public string Name { get; set; }
    }

0 个答案:

没有答案