简体   繁体   English

使用一个实现的接口来实例化具有多个接口的泛型类

[英]Use one implemented interface to instantiate Generic class with multiple interface

I have a generic method which using multiple interfaces,我有一个使用多个接口的通用方法,

public T GetZonePrices<T>() where T : IRegionalZonePrice, INationalZonePrice, new()
{
// codes here
}

Then, I have a class that will be used to replace the T. It only implement one interface.然后,我有一个将用于替换 T 的类。它只实现一个接口。

public class MarketRegionalZonePrice : IRegionalZonePrice
{
// properties here
}

How do you use the generic method by passing the class which only implemented one of the interfaces?您如何通过传递仅实现其中一个接口的类来使用泛型方法?

var result = GetZonePrices<MarketRegionalZonePrice>();

It gives me error,它给了我错误,

"The type .. cannot be used as parameter type 'T' in the generic type or method .. . There is no implicit reference conversion from .. to .. ." “类型 .. 不能用作泛型类型或方法中的参数类型 'T' .. . 没有从 .. 到 .. 的隐式引用转换。

As mentioned in the comments, you can't.正如评论中提到的,你不能。

What you could do though is:你可以做的是:

public inteface IZonePrice 
{
// codes here
}
public interface IRegionalZonePrice : IZonePrice  
{
// codes here
}
public interface INationalZonePrice : IZonePrice 
{ 
// codes here
}

public T GetZonePrices<T>() where T :IZonePrice, new()
{
// codes here
}

Then this would work:那么这将起作用:

public class MarketRegionalZonePrice : IRegionalZonePrice
{
// properties here
}

...

var result = GetZonePrices<MarketRegionalZonePrice>()

if need be you can check the type of T with T is IRegionalZonePrice or T is INationalZonePrice如果需要,您可以检查T的类型,其中T is IRegionalZonePriceT is INationalZonePrice

Is there much different between these interfaces?这些接口之间有很大不同吗? Because it almost looks to me that you overcomplicated your business model / logic?因为在我看来,您的业务模型/逻辑几乎过于复杂?

You probably just need the interface IZonePrice and then your implementation will be public class RegionalZonePrice : IZonePrice and public class NationalZonePrice : IZonePrice with the respective different values for each Zone.您可能只需要IZonePrice接口,然后您的实现将是public class RegionalZonePrice : IZonePricepublic class NationalZonePrice : IZonePrice ,每个区域具有各自不同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM