gpt4 book ai didi

c# - 在类型上强制执行静态方法

转载 作者:太空狗 更新时间:2023-10-30 00:55:58 26 4
gpt4 key购买 nike

我希望一个类具有一个名为 GetProduct 的强制静态方法,以便客户端代码可以接受一个类型,并在检查传递的类型实现了一个名为 ICommandThatHasProduct 的接口(interface)后安全地调用该静态方法。

这似乎是不可能的,所以现在我正在寻求帮助以找到实现这一目标的方法。我知道我可以使用反射来查看我传递的类型是否包含一个名为“GetProduct”的方法,但我希望有一种更面向对象的方式(即使用继承)。

任何帮助将不胜感激!下面的代码是伪c#,肯定编译不过。

public interface ICommandThatHasProduct
{
object GetProduct(int id);
}

public abstract class Command : ICommandThatHasProduct
{
// I want to be able to make the GetProduct method static
// so that calling code can safely call it
public static object GetProduct(int id)
{
// do stuff with id to get the product
}

public object Execute()
{
CommandWillExecute();
}

public abstract object CommandWillExecute();
}

public class Program
{
public Program(Type type, int productId)
{
if(type == ICommandThatHasProduct)
{
// Create the args
var args = object[1]{ productId };

// Invoke the GetProduct method and pass the args
var product = type.InvokeMethod("GetProduct", args);

//do stuff with product
}

throw new Execption("Cannot pass in a Command that does not implement ICommandHasProduct");
}
}

最佳答案

方法不必是静态的。改用成员方法,并创建通常的继承树。

我猜您正在寻找 abstract factory或 C# 中的简单工厂方法模式实现。

保留 LSP心里。它有助于避免看起来很奇怪的继承树。

关于c# - 在类型上强制执行静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8889232/

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