简体   繁体   English

返回派生类的泛型方法引发对象必须实现IConvertible异常

[英]Generic method returning derived class throws Object must implement IConvertible exception

I have a base class: 我有一个基类:

public class TestBase
{
}

I have a derived class 我有一个派生类

public class TestDerived: TestBase
{
}

I have a generic method 我有一个generic method

  public class SomeClass
  {
   public T GetInstance()
   {
      var inst=new TestDerived();
      return (T)Convert.ChangeType(inst, typeof(T)); //exception thrown here
   }
  }

I make a call: 我打个电话:

    SomeClass test=new SomeClass()
    var x= test.GetInstance<TestBase>(); 

Why do I get an exception saying System.InvalidCastException : Object must implement IConvertible. 为什么会出现异常,提示System.InvalidCastException : Object must implement IConvertible.

By using constraints you can let the compiler know T is based off TestBase. 通过使用约束,您可以让编译器知道T基于TestBase。 This way you get to avoid losing type checking. 这样您就可以避免丢失类型检查。

public class SomeClass
{
   public T GetInstance() where T : TestBase
   {
      var inst=new TestDerived();
      return inst;
   }
}

But why do you need to use generics at all? 但是,为什么根本需要使用泛型? There's nothing here that benefits from it. 这里没有什么可以从中受益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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