没有实例的接口方法

时间:2014-04-17 19:43:08

标签: c# class generics inheritance interface

所以标题听起来很奇怪,但是(至少我认为有)我疯狂背后的原因。我想从类中调用一个接口的方法,而不必创建类的实例;完全像一个静态方法,但我想添加一些我认为的泛型。

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 );

我理解这个问题听起来有多愚蠢,并且接口中不可能有静态方法。但是,为了科学和整个社会的教化,还有更好的方法吗?感谢您的时间和任何建议。

2 个答案:

答案 0 :(得分:0)

我认为实现这一目标的唯一方法是继承基类而不是接口选项。类似的东西:

public class BaseClass
{
    public static BaseClass NewSelf()
    {
        return new BaseClass();
    }
}

public class TestClass : BaseClass
{

}

然后使用它:

TestClass newItem = (TestClass)BaseClass.NewSelf();

答案 1 :(得分:0)

  

为了科学和整个社会的教化,还有更好的方法吗?

是。 关注点分离表示您应该使用可以实例化的其他类来从流中加载其他类,而不是将同一个类用于多个目的。

interface ISaveObjects<T>
{
    Stream Save(T obj);
}

interface ILoadObjects<T>
{
    T Load(Stream stream);
}

public class MyClassStreamer : ISaveObjects<MyClass>, ILoadObjects<MyClass>
{
    public MyClass Load(Stream stream)
    {
        // Deserialize the stream and load data into new instance
    }

    public Stream Save(MyClass obj)
    {
        Stream stream;

        // Serialize "obj" and write to stream

        return stream;
    }
}