gpt4 book ai didi

c# - 如何创建具有可变参数/不同方法签名的方法接口(interface)?

转载 作者:可可西里 更新时间:2023-11-01 03:12:10 24 4
gpt4 key购买 nike

我正在尝试创建一个通用类的接口(interface),但实现类可以有不同的参数。

例如

public interface IViewModel
{
//...
void ResetReferences();
}

// and then, in my class implementations, something like this:
public class LocationViewModel : IViewModel
{
public void ResetReferences(List<StateProvinces> stateProvinces) //...
}

public class ProductViewModel : IViewModel
{
public void ResetReferences(List<Color> colors, List<Size> sizes) //...
}

请注意,我想对 ResetReferences 命名约定进行标准化。我很确定我不能这样做,但是有没有可行的设计模式?例如在我的界面中,像下面这样的东西?

// variable parameters
void ResetReferences(params object[] list);

但是我该如何进行类型检查或让它调用我想要的实际方法签名等?

也许接口(interface)是错误的使用方式?也许只是一个基类和一些编码约定?

谢谢,

最佳答案

用实现相关接口(interface)的对象替换您的参数列表:

public interface IViewModel
{
//...
void ResetReferences(IResetValues vals);
}

我应该补充一点,IMO,ResetReferences() 不应该接受参数...它应该重置为某个默认值,该默认值特定于实现您的接口(interface)的各个类型...“重置”这个词对我来说意味着“恢复到初始状态”...添加 args 意味着您可以控制它。

关于c# - 如何创建具有可变参数/不同方法签名的方法接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6114519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com