简体   繁体   中英

C# Interface/Abstract Class with Dynamic Type

I'm writing a series of math based class that each inherit from an abstract class. I want my abstract class to have a getter and setter called Parameters.

public abstract dynamic Parameters {get; set;}

Then in each individual math class I want to implement Parameters with a certain type:

If the class requires a period I would do it like this:

public override IPeriod Parameters {get; set;}

This doesn't compile. Obviously I could change the return type to dynamic and it would work, but then I lose intellisense. Is there a standard way of doing this without losing intellisense?

Every one of the class will have a Parameters {get; set;} but they will be up a different type. Is it better just to eliminate Parameters from the abstract class?

Yes, use generics..

public MyAbstractBaseClass<T>
{
    public abstract T Parameters {get; set;}
}

then you can inherit specifying the type that will be used for the param like..

public PeriodClass : MyAbstractBaseClass<IPeriod>
{
    public override IPeriod Parameters {get; set;}
}

如果您将参数设置为泛型,则可以返回所需的任何类型:

public abstract T Parameters<T> {get; set;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM