【问题标题】:Interface Method without an Instance没有实例的接口方法
【发布时间】: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 );

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

【问题讨论】:

  • 你的要求很奇怪。如果您能说出您要解决的实际问题是什么,我们会更好地回答?以及实例有什么问题?
  • 看看this post
  • 那篇文章很完美。它对接口为什么不允许静态方法进行了极其广泛的思考。我做了一些研究,但那个帖子胜过它,所以谢谢你!

标签: c# class generics inheritance interface


【解决方案1】:

为了科学和整个社会的教化,有没有更好的方法来做到这一点?

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

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

【讨论】:

  • 是的,我喜欢你的想法。我讨厌将它分离出来并创建一个类来为所有“MyClass”es 实现 Load 方法的想法。但我宁愿完成这个项目,然后陷入一个相当平凡的问题。谢谢+edit:我喜欢那个工厂的想法
  • @Dandruff:尽管你讨厌这个想法,但它实际上是一个很好的设计原则。它增加了您发现“流”类型之间的共性并能够更好地重用代码的可能性。它降低了加载/保存对象方式的改变最终导致你重写一半代码库的可能性。
  • 实际上,当你把它放在那个角度时,它确实很有意义......我从来没有因为我的无知而重写大量代码...... 畏缩再次感谢您!
【解决方案2】:

我认为实现这一点的唯一方法是继承基类而不是接口选项。比如:

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

public class TestClass : BaseClass
{

}

然后使用它:

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

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    相关资源
    最近更新 更多