c# - c# 不能从'IInterface 强制转换' to 'IInterface - 将没有泛型的类转换为具有泛型的接口
问题描述
我有接口IJob
,这是我的许多功能中的一个参数。但是这个接口实际上是通用的(IJob<T>
)。我想避免将通用参数传递给所有函数。所以我做了如下的事情:
public interface ISomeType
{
string X { get; set; }
}
public interface IJob<T>
where T : ISomeType
{
string SomeProp { get; set; }
T GenericProp { get; set; }
}
public interface IJob : IJob<ISomeType> { }
public class Job<T> : IJob<T>
where T : ISomeType
{
public string SomeProp { get; set; }
public T GenericProp { get; set; }
}
public class Job : Job<ISomeType> { }
public class SomeOtherType : ISomeType
{
public string X { get; set; }
public string Y { get; set; }
}
所以我的函数现在看起来像这样:
public void DoSomething(IJob job){}
//instead of:
public void DoSomething<T>(IJob<T> job)
where T:ISomeType {}
我想这样做是因为这些功能永远不会触及GenericProp
- 他们只需要知道那T
是ISomeType
一切正常,但我发现以下内容不起作用:我想将所有作业存储在 a 中IDictionary<string,IJob> jobs
,但我不知道GenericProp
运行前的类型。所以我需要转换一个Job<T>
toIJob
才能将它添加到字典中,但这会引发转换错误。
IJob job = (IJob)new Job<SomeOtherType>();
总的来说,我不觉得我的解决方案是最佳实践。但是我该如何使用多态类呢?
解决方案
推荐阅读
- ms-access - MS-ACCESS - 在插入之前/之后插入/更新触发器需要
- java - Java 子类与超类
- node.js - 如何将参数传递给sails-hook-cron中的作业
- python - 根据每个中的空值数选择数据框列
- cron - 如何自动运行ffmpeg命令
- jinja2 - Jinja2 - 拆分字符串
- c# - 在 Visual C# 中运行时编译
- multithreading - 如何停止新对象中的 goroutine?
- active-directory - LDAP Active Directory 是否可以具有不同的 sn 和 givenName 但名称相同
- regex - VBA RegEx - 匹配所有非字母数字字符但忽略空格