ITPub博客

首页 > 应用开发 > > 如何传递动态类型到TModel类型的泛型参数中?

如何传递动态类型到TModel类型的泛型参数中?

作者:penny_liang 时间:2019-08-27 09:16:01 0 删除 编辑

有下面一段C#代码,是否有办法将错误排除?

目的是想要:根据类型名称后去类型,并将类型传递给Employee<TModel>的TModel。这里VS会检查报错说 变量不能当做类型使用。是否有什么版本将次错误排除?或者有没有其他的办法事项相同的效果?

using System;
using System.Linq;
using System.Reflection;

namespace Mike.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Specified Type Transform to TModel type generic parma
            Personal specifiedPersonal = new Personal();

            Employee<Personal> employee = new Employee<Personal>();
            employee.DoSth();
            #endregion

            #region 如何动态传递类型?
            Assembly assmebly = typeof(Personal).GetTypeInfo().Assembly;
            Type dynamicType = assmebly.ExportedTypes.Where(x => x.Name == "Personal").FirstOrDefault();
            Employee<dynamicType> dynamicEmployee = new Employee<dynamicType>();
            dynamicEmployee.DoSth();
            #endregion           

            Console.ReadLine();
        }
        public class Personal
        {
            public string FirstName { get; internal set; }
            public string LastName { get; internal set; }
        }
        public class Employee<TModel>
        {
            public void DoSth()
            {
                Console.WriteLine("Done !!!"); ;
            }
        }
    }    
}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/714/viewspace-3122954/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-12

  • 博文量
    189
  • 访问量
    1736