首页 > 解决方案 > 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- 他们只需要知道那TISomeType

一切正常,但我发现以下内容不起作用:我想将所有作业存储在 a 中IDictionary<string,IJob> jobs,但我不知道GenericProp运行前的类型。所以我需要转换一个Job<T>toIJob才能将它添加到字典中,但这会引发转换错误。

IJob job = (IJob)new Job<SomeOtherType>();

总的来说,我不觉得我的解决方案是最佳实践。但是我该如何使用多态类呢?

标签: c#.netgenericsinterface

解决方案


推荐阅读