我希望类有一个名为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'方法并不真正适用于一般的面向对象的概念。 – 2012-01-17 03:15:05
有没有静态继承,所以反射可能是唯一的方法 – BrokenGlass 2012-01-17 03:16:10
可能重复的[c#:继承/接口静态成员?](http://stackoverflow.com/questions/1128361/c-inherited-interface-static-member )事实上,几乎所有的[这些问题](http://stackoverflow.com/search?q=%5Bc%23%5D+static+interface)已经解决了这个问题。 – 2012-01-17 03:26:11