【发布时间】:2014-06-02 06:01:59
【问题描述】:
所以标题听起来很奇怪,但我的疯狂背后有(至少我认为有)一个原因。我想从类中调用接口的方法,而不必创建类的实例;完全像一个静态方法,但我想添加一些我认为的泛型。
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 );
我理解这个问题听起来多么愚蠢,而且在接口中不可能有静态方法。但是为了科学和整个社会的教化,有没有更好的方法来做到这一点?感谢您的宝贵时间和任何建议。
【问题讨论】:
-
你的要求很奇怪。如果您能说出您要解决的实际问题是什么,我们会更好地回答?以及实例有什么问题?
-
那篇文章很完美。它对接口为什么不允许静态方法进行了极其广泛的思考。我做了一些研究,但那个帖子胜过它,所以谢谢你!
标签: c# class generics inheritance interface