反射实例化不同类型的实例

项目中经常会用反射来实例化对象,根据参数不同实例化不同类型的实例;

1,定义接口

public interface IOtherAudit
{ ResultDTO GetResult(AuditUserDTO userDto); }

2,根据需要实现两套接口

public class Test1_AuditService : IOtherAudit
{
        public AuditResultDTO GetResult(AuditUserDTO userDto)
        {
          //TODO:业务逻辑代码
        }
}
public class Test2_AuditService : IOtherAudit
{
        public AuditResultDTO GetResult(AuditUserDTO userDto)
        {
          //TODO:业务逻辑代码
        }
}

3,反射得到相关实例

public AuditResultDTO GetResult(AuditUserDTO userDto)
 {
      //获取需要实例化的类型
      Type type = Type.GetType("demo.test.Service." + userDto.typeName + "Service,demo.test.Service");
      //实例化对象
      IOtherAudit service = Activator.CreateInstance(type) as IOtherAudit;
      //获取审核结果
      AuditResultDTO result = service.GetResult(userDto);
return result; }

 

posted @ 2019-07-22 16:33  Gylianger  阅读(241)  评论(0编辑  收藏  举报