C#限制重写方法以返回特定类型

时间:2017-11-17 12:37:09

标签: c# abstract-class

我有一个抽象类,它应该有一个返回类实例的方法,该类应该从基类继承并实现接口。

public abstract class AbstractClass
{
    abstract [DonotKnowTheType] GetClassInstance() //The Return type should be an instance of a class which implements TestClass and ISample 
}

public class ChildClass : AbstractClass
{
    override [DonotKnowTheType] GetClassInstance()
    {
        //Need to return instance of SampleClass in this example. This could vary, this should be an instance of a class which implements TestClass and ISample
    }
}

public class SampleClass : TestClass,ISample
{
    //Implementation
}

请通过良好的设计帮助实现这一目标。需要限制在ChildClass中编写重写方法的开发人员只返回实现TestClass和ISample的类的实例。如果没有,则必须显示编译时错误。

2 个答案:

答案 0 :(得分:1)

试试这个:

public abstract class TheEnforcer<T> where T: TestClass, IMyInterface
    {
        protected abstract T GetClassInstance();
    }

    public class ThePoorClass : TheEnforcer<DerivedTestClass>
    {
        protected override DerivedTestClass GetClassInstance()
        {
            throw new NotImplementedException();
        }
    }

    public class TestClass
    {

    }

    public class DerivedTestClass : TestClass, IMyInterface
    {

    }

    public interface IMyInterface
    {

    }

发表评论后:

namespace First {
    public abstract class TheEnforcer<T> where T : IMarkerInterface
    {
        protected abstract T GetClassInstance();
    }    

    public interface IMarkerInterface
    {

    } }

namespace Second {
    using First;

    // All this is in separate name space
    public class TestClass: IMarkerInterface
    {

    }

    public class DerivedTestClass : TestClass, IMyInterface
    {

    }

    public interface IMyInterface
    {

    }

    public class ThePoorClass : TheEnforcer<DerivedTestClass>
    {
        protected override DerivedTestClass GetClassInstance()
        {
            throw new NotImplementedException();
        }
    } }

答案 1 :(得分:1)

您可以使用TestClassISample上的contraint使您的抽象类具有通用性:

public abstract class AbstractClass<T> where T: TestClass, ISample
{
    public abstract T GetClassInstance(); //The Return type should be an instance of a class which implements AbstractClass and ISample 
}

public class ChildClass : AbstractClass<SampleClass> 
{
    public override SampleClass GetClassInstance()
    {
        //Need to return instance of SampleClass in this example. This could vary, this should be an instance of a class which implements AbstractClass and ISample
        return new SampleClass();
    }
}