简体   繁体   中英

C# Generic Class, how can I use public properties of derived class of type parameter?

I have two classes in C#:

public abstract class BaseAccount
{
    public void MyMethod1()
    {
        //Code
    }
}

public class DerivedAccount : BaseAccount
{
    public  void MyMethod2()
    {
        //code
    }
}

public class AccountBL<T> where T : BaseAccount, new()
{
    public void TestMethod()
    {
        T obj1 = new T();
        obj1.MyMethod1();
        obj1.MyMethod2(); //Wrong!!! Can I use a method in derived class without changing constaint??
    }       
}    

How can I use public properties of a derived class in the generic class?

I don't want implement several generic class for each of my Derived Class.

Define an interface that includes the members you want to access, and then restrict the type parameter to types that implement that interface.

public IMyInterface {
  void MyMethod2();
}

public class AccountBL<T> where T : BaseAccounbt, new(), IMyInterface {
  // Members can access T.MyMethod2()
}

Unlike other some languages, C# only allows reference to members on type parameters that fit the requirements imposed on the type parameters.

If you want to use DerivedAccount.Method2() , this wish already is a constraint. You obviously need T to be DerivedAccount.

You could do something like that:

 (obj1 as DerivedAccount)?.MyMethod2();

but I personally don't like to mix type casts and generics. If your method is generic, it means you don't care about the specific runtime type (except it should be BaseAccount ). Then adding type checks seems a little odd.

It is because your Structure. With where T : BaseAccount, new() your're saying that T has to inherit from BaseAccount so you can use the methods from BaseAccount . If you want to use the Methods from DerivedAccount you have to check this first:

if (obj1 is DerivedAccount ) {}

And than cast it as DerivedAccount . so you get the following:

public class AccountBL<T> where T : BaseAccount, new()
{
    public void TestMethod()
    {
        T obj1 = new T();
        obj1.MyMethod1();

        if (obj1 is DerivedAccount )
        {
             (obj1 as DerivedAccount).MyMethod2();
        }
    }       
} 

Here you have an executable example: https://dotnetfiddle.net/NwxPRt

It is because your Structure. With where T : BaseAccount, new() your're saying that T has to inherit from BaseAccount so you can use the methods from BaseAccount . If you want to use the Methods from DerivedAccount you have to check this first.

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