简体   繁体   中英

How to return derived class with C# generics

I am trying to generate some test data using NBuilder for automation for all the classes that extends a base class wherein each class will have different fields.

Here is my code:

public interface Interface
{
    T method<T>() where T : BaseClass;
}

public class DrivedClass: BaseClass,Interface
{
    public T method<T>() where T : BaseClass
    {
        var derviedObj = Builder<DrivedClass>.CreateNew().Build();

        return derviedObj;
    }
}

return derviedObj giving error cannot implicity convert derviedObj to T

I'm not really familiar with nbuilder, but it looks like you could try something like this:

public class DrivedClass: BaseClass,Interface
{
    public T method<T>() where T : BaseClass
    {
        var derviedObj = Builder<T>.CreateNew().Build();

        return derviedObj;
    }
}

Or this, if that's what you're really after:

public class DrivedClass: BaseClass,Interface
{
    public T method<T>() where T : BaseClass
    {
        var derviedObj = Builder<DrivedClass>.CreateNew().Build();

        return derviedObj as T;
    }
}

Then you will get T , but there's really no chance of knowing that it will succeed. What happens when you add another implementation that doesn't inherit DrivedClass ?

public class MoreDrivedClass : BaseClass, FooInterface
{

}

Then this cast will fail:

var drivedClass = new DrivedClass();
var foo = drivedClass.method<MoreDrivedClass>();

Then you will not be able to cast DrivedClass to MoreDrivedClass . Foo will be null.

The method can't return DerivedClass because there is no way to know if T is that class or some other one:

SomeOtherDerived v = (new DrivedClass()).method<SomeOtherDerived>(); 

It is not clear what you trying to achieve, possibly something like following sample:

public interface Interface<T> where T : BaseClass
{
    T method();
}

public class DrivedClass: BaseClass,Interface<DerivedClass>
{
  public DerivedClass method()
  {
      DerivedClass derviedObj = Builder<DrivedClass>.CreateNew().Build();
      return derviedObj ;
  }
}

Try with Activator.CreateInstance.

public class DrivedClass: BaseClass,Interface
{
  public T method<T>() where T : BaseClass
    {
      var derviedObj = Activator.CreateInstance(typeof(T));
      return (T)derviedObj ; 

    }
}


 DrivedClass drOb = new DrivedClass ();
 var v = drOb.method<desiredType_T>();

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