如何创建静态基础方法中继承的实例? [英] How to create instance of inherited in static base method?

查看:48
本文介绍了如何创建静态基础方法中继承的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从实例中,我可能会这样做.

From an instance, I might do this.

 var obj= Activator.CreateInstance(GetType());

虽然不确定如何在静态基本方法中获取继承类的typeof.

Not sure how to get typeof of the inherited class in a static base method though.

这是最好的前进方式吗?

Is this the best way forward?

 public static Method<T>() where T : SomeBase, new()

推荐答案

没有诸如派生静态方法之类的东西.因此,无法创建一个静态工厂方法来返回不同的类型,该方法取决于您在哪个派生类上调用它.

There is no such thing as a derived static method. So there is no way to create a static factory method that returns a different type depending on which derived class you call it on.

如Lonli-Lokli所建议,您应该使用抽象工厂设计模式.

As Lonli-Lokli suggested, you should use the Abstract Factory design pattern.

public interface ISomething
{
    void DoSomething();
}

public class SomeClass : ISomething
{
    public virtual void DoSomething() { Console.WriteLine("SomeClass"); }
}

public class SomeDerivedClass : SomeClass
{
    private int parameter;

    public SomeDerivedClass(int parameter)
    {
        this.parameter = parameter;
    }

    public virtual void DoSomething()
    {
        Console.WriteLine("SomeDerivedClass - {0}", parameter);
        base.DoSomething();
    }
}

public interface IFactory
{
    public ISomething Create();
}

public class SomeClassFactory : IFactory
{
    public ISomething Create() { return new SomeClass(); }
}

public class SomeDerivedClassFactory : IFactory
{
    public ISomething Create() { return new SomeDerivedClass(SomeParam); }

    public int SomeParam { get; set; }
}

Abstract Factory与静态Factory方法的优点:

  • 它更加灵活,可以为抽象工厂的每个实现者实现工厂逻辑的新实现(可能要复杂得多).如果需要,您每个班级可以拥有一个以上的工厂.
  • 由于您没有调用静态方法,因此在运行时替换起来要容易得多.这对于在单元测试中注入模拟非常有用.

优点很多.即使可以使静态方法按您希望的方式工作,抽象工厂在各个方面都优于静态工厂方法.

The pros are huge. Abstract Factories are superior to static factory methods in every way, even if you could get static methods to work the way you want them to.

抽象工厂与静态工厂方法的缺点:

  • 抽象工厂的用户必须具有工厂实例才能创建派生类型.
  • 您必须为每个派生类编写一个新的抽象工厂实现.

缺点非常有限.

用户实例化工厂以创建单个对象非常容易:

It is extremely easy for a user to instantiate a factory to create a single object:

MyClass myClass = new MyClassFactory().Create();

关于工厂实现中的代码重复:节省实现者一点点输入是没有意义的.编写程序的目标是编写可以阅读,理解和轻松修改的代码.没有节省纸张或按键的编程目标:)

As for code duplication in the factory implementation: Saving the implementer a tiny bit of typing is pointless. It is a goal in programming to write code that can be read, understood, and easily modified. There is no programming goal to save paper or keystrokes :)

这篇关于如何创建静态基础方法中继承的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆