所以标题听起来很奇怪,但是(至少我认为有)是我疯狂背后的原因。我想从类中调用接口的方法,而不必创建类的实例;完全像一个静态方法,但我想添加一些我认为的泛型。没有实例的接口方法
interface ISaveMyself
{
Stream Save();
// If I could force this to be static, it would fix my problem
Object Load(MyClass instance);
}
class MyClass
{
#region Implementing ISaveMyself
public Stream Save()
{
Stream stream;
// Serialize "this" and write to stream
return stream;
}
// Implements my interface by calling my static method below
Object ISaveMyself.Load(Stream stream)
{
return MyClass.Load(stream);
}
#endregion Implementing ISaveMyself
// Static method in the class because interfaces don't allow static
public static Object Load(Stream)
{
Object currentClass = new MyClass();
// Deserialize the stream and load data into "currentClass"
return currentClass;
}
}
然后,我本来想要做这样的事情称之为:
Type myClassType = typeof(MyClass)
// This would never work, but is essentially what I want to accomplish
MyClass loadedClass = (myClassType as ISaveMyself).Load(stream);
我理解这个问题是多么愚蠢的声音,那是不可能在接口的静态方法。但为了科学和整个社会的熏陶,有没有更好的方法来做到这一点?感谢您的时间和任何建议。
你要求的是奇怪的。如果你能说出你想要解决的实际问题,那对我们来说会更好。实例有什么问题? –
看看[这篇文章](http://stackoverflow.com/questions/259026/why-doesnt-c-sharp-allow-static-methods-to-implement-an-interface) – tophallen
该帖子是完美的。对于接口不允许使用静态方法的原因有着非常广泛的思考。我做了一些研究,但这篇文章胜过它,所以谢谢你! – Dandruff