简体   繁体   English

C#泛型方法重载

[英]C# Generic method overloading

I have problem with C# generics. 我对C#泛型有疑问。 I need do something like this, in PCL. 我需要在PCL中执行类似的操作。

class Factory<T> : IFactory<T>
{
    T Create()
    {
          throw new NotSupportedException();
    }
}

class Factory : IFactory<MyClass>
{
    MyClass Create()
    {
         return new MyClass();
    }
}

//In some method ....
IFactory<MyClass> factory = new Factory<MyClass>();
MyClass variable = factory.Create(); //This throw NotSupportedException

I know this is bulshit, but I try many solutions and no of them work :-( 我知道这是胡说八道,但我尝试了许多解决方案,但它们都不起作用:-(

You're creating an instance of Factory<T> , not Factory . 您正在创建Factory<T>的实例,而不是Factory Factory<T>.Create throws an exception, so the behavior you're seeing is normal. Factory<T>.Create引发异常,因此您看到的行为是正常的。

You should use Factory instead of Factory<T> . 您应该使用Factory而不是Factory<T>

Another option is to add a new constraint on T in Factory<T> : 另一个选择是在Factory<T>T添加new约束:

class Factory<T> : IFactory<T> where T : new()
{
    public T Create()
    {
          return new T()
    }
}

The Factory<T> class doesn't serve any purpose in your example, since your Factory is inheriting directly from IFactory<T> . 在您的示例中, Factory<T>类没有任何作用,因为Factory直接从IFactory<T>继承。 If you're going to do that, you can just delete the first class, and do this: 如果要这样做,您可以删除第一类,然后执行以下操作:

IFactory<MyClass> factory = new Factory();
MyClass variable = factory.Create();

The reason you're getting an exception is because you're creating an instance of Factory<T> , and that is defined to throw an exception when .Create() is called on it. 收到异常的原因是因为您正在创建Factory<T>的实例,并且该实例被定义为在.Create()时引发异常。

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

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