【发布时间】:2012-02-11 22:31:31
【问题描述】:
我希望一个类有一个名为 GetProduct 的强制静态方法,以便客户端代码可以接受一个类型并在检查传递的类型是否实现了一个名为 ICommandThatHasProduct 的接口后安全地调用该静态方法。
这似乎是不可能的,所以现在我正在寻求帮助以找到实现这一目标的方法。我知道我可以使用反射来查看我传递的类型是否包含一个名为“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");
}
}
【问题讨论】:
-
static方法并不真正适用于一般的 OO 概念。 -
没有静态继承,所以反射可能是唯一的方法
-
c#: Inherited/interface static member? 的可能重复项事实上,几乎所有these questions 都已经解决了这个问题。
标签: c# inheritance polymorphism static-methods