加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用Generic Cast to Interface的C#Factory方法

发布时间:2020-12-16 09:41:30 所属栏目:百科 来源:网络整理
导读:我有以下课程: // -- model hierarchypublic interface IJob {}public abstract class AbstractJob : IJob {}public class FullTimeJob : AbstractJob { }// -- dao hierarchypublic interface IJobDaoT where T : IJob { T findById(long jobId); long ins
我有以下课程:

// -- model hierarchy
public interface IJob {
}

public abstract class AbstractJob : IJob {
}

public class FullTimeJob : AbstractJob {               
}

// -- dao hierarchy
public interface IJobDao<T> where T : IJob {       
  T findById(long jobId);
  long insert(T job);
}

public interface IFullTimeJobDao : IJobDao<FullTimeJob> {        
}

public abstract class AbstractDao {    
}

public abstract class AbstractJobDaoImpl<T> : AbstractDao,IJobDao<T> where T : IJob {
  public T findById(long jobId) {
    // omitted for brevity
  }

  public long insert(T job) {
    // omitted for brevity
  }
}

public class FullTimeJobDaoImpl : AbstractJobDaoImpl<FullTimeJob>,IFullTimeJobDao {
}

我从工厂方法调用以下代码,这似乎不起作用:

public IJobDao<IJob> createJobDao(long jobDaoTypeId)
{
    object jobDao = Activator.CreateInstance(typeof(FullTimeJobDaoImpl));
    return jobDao as IJobDao<IJob>; // <-- this returns null
    return (IJobDao<IJob>) jobDao; // <-- this cast fails
}

这种“向上演员”是如何正确实现的?

解决方法

要使此转换成为可能,您需要将接口类型参数标记为out:

public interface IJobDao<out T> where T : IJob {...}

然后

object jobDao = Activator.CreateInstance(typeof(FullTimeJobDaoImpl));
var r = jobDao as IJobDao<IJob>; //not null

但这会给界面带来一些限制.阅读out (Generic Modifier) (C# Reference)以获取更多信息.

In a generic interface,a type parameter can be declared covariant if
it satisfies the following conditions:

  1. The type parameter is used only as a return type of interface methods and not used as a type of method arguments.
  2. The type parameter is not used as a generic constraint for the interface methods.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读