C#用反射創建抽象類實例,方便業務層調用,松耦合

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011511086/article/details/81980974

程序初始化的業務實例可以切換為其他實例層,實現插口效果

namespace IDao
{
    public class DaoBase<T> where T : class
    {
        /// <summary>
        /// 返回抽象類的具體實例
        /// </summary>
        public readonly static T Instance;          
    }
}

namespace IDao
{
    public abstract class IRoleDao: DaoBase<IRoleDao>
    {
        public abstract List<string> GetRoleName();
    }
}


namespace MysqlDao
{
    public  class RoleDao: IRoleDao
    {
        public override List<string> GetRoleName()
        {
            List<string> list = new List<string>();
            list.Add("管理員");
            list.Add("督戰隊");
            list.Add("救火隊");
            return list;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        //程序啟動,初始化抽象類實例
        Assembly assembly = Assembly.Load("MysqlDao");
        Type[] typeArr = assembly.GetTypes();
        foreach (Type item in typeArr)
        {
            //實現類父級接口
            Type interfaceT = item.BaseType;
            //接口父級DaoBase
            Type daobase = interfaceT.BaseType;
            FieldInfo daobase_instance = daobase.GetField("Instance");
            var daoInstance = Activator.CreateInstance(item);
            daobase_instance.SetValue(interfaceT, daoInstance);
        }
        //調用方法,在業務層調用示例:        
        //var listName = IRoleDao.Instance.GetRoleName();
    }
}   

猜你喜欢

转载自blog.csdn.net/u011511086/article/details/81980974