[英]Interface method has interface argument but want to use class argument in the implementation
我們有一組組件,每個組件都應該以自己的方式加載。
考慮以下:
public interface IComponent
{
Type LoaderType {get;}
}
public class ComponentA: IComponent
{
Type LoaderType => typeof(ComponentALoader);
}
public class ComponentB: IComponent
{
Type LoaderType => typeof(ComponentBLoader);
}
public interface ILoader
{
void Load(IComponent example);
}
有沒有辦法讓我在實現ILoader
時可以在加載器中使用組件類型而不是接口(以避免強制轉換)?
例子:
public class ComponentALoader: ILoader
{
void Load(ComponentA component) {}
}
public class ComponentBLoader: ILoader
{
void Load(ComponentB component) {}
}
[編輯:這是當前有效的實現,但需要在每個加載器中進行強制轉換]:
public class ComponentALoader: ILoader
{
void Load(IComponent component)
{
// This is the cast that I was looking to avoid in favor of having the type in the method signature
var compA = (ComponentA) component;
doSomethingWithA();
}
}
public class ComponentBLoader: ILoader
{
void Load(IComponent component)
{
// This is the cast that I was looking to avoid in favor of having the type in the method signature
var compB = (ComponentB) component;
doSomethingWithB();
}
}
public class ComponentBLoader: ILoader
{
void Load(ComponentB component) {}
}
入口點類似於:
List<IComponent> components = listOfComponents;
foreach (var component in components)
{
// Retrieves the correct loader from a list of loaders
// based on the type property on the components
var loader = getLoaderForComponent(component);
loader.Load(component);
}
編輯: 1) 值得注意的是,我們在這里很容易談論 100 多個組件及其相關的加載器,因此對於每個組件具有重載方法的加載器 class 並不是我們想要的 go
2) 加載器列表是使用 DI 提供給主加載器的,我不完全確定我們將如何使用通用接口來做到這一點。 可能是啟用 DI 的ILoader
接口,然后ILoader<T>
與 Load 方法。 不知道如何從給定的 ILoader 調用ILoader
來調用ILoader<T>
上的方法。
3) tl;dr 我們希望避免主加載器知道許多類型的組件和加載器
4)當前的解決方案有效,也許在每個裝載機中進行強制轉換是必要的
讓我們看看我對你的問題的理解程度。 正如評論中所說,為了避免強制轉換,您可以使您的接口通用並在實現類中定義通用類型:
public interface IComponent
{
Type LoaderType { get; }
}
public class ComponentA : IComponent
{
public Type LoaderType => typeof(ComponentALoader);
}
public class ComponentB : IComponent
{
public Type LoaderType => typeof(ComponentBLoader);
}
public interface ILoader<T> where T : IComponent // This restriction allows only types that implement the interface inside the load method
{
void Load(T example);
}
public class ComponentALoader : ILoader<ComponentA>
{
public void Load(ComponentA component) { }
}
public class ComponentBLoader : ILoader<ComponentB>
{
public void Load(ComponentB component) { }
}
此代碼編譯,您可以使用Load
方法中的類型而不是接口
您必須使用通用 class
public class Component<T> wher T:IComponent
{
void Load(T component) {}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.