一般有多个约束 [英] Generic with multiple constraints

查看:115
本文介绍了一般有多个约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用一个类似于下面的定义的方法(简化以避免混淆):

  public静态无效注册< T>(T值)其中T:BaseClass,IInterface 

因为我有一个定义这两个值的类实例。当我将一个`BaseClass'传递给一个方法,然后尝试在上面的声明中使用该实例时,就会出现问题。例如:

  public class MyClass 
{
public MyClass(BaseClass value)
{
注册(值);




$ b我可以传递一个类的实例, BaseClass和IInterface放入构造函数中,但是当我尝试在 Register 方法中使用该值时,出现编译错误,指出:


类型'BaseClass'不能用作泛型类型或方法'Register(T)'中的类型参数'T'。没有从'BaseClass'到'IInterface'的隐式引用转换。

如果我在构造函数中更改类型,如下所示:

  public class MyClass 
{
public MyClass(IInterface value)
{
寄存器(值);


我收到一个错误消息:


类型'IInterface'不能用作泛型类型或方法'Register(T)'中的类型参数'T'。没有从'IInterface'到'BaseClass'的隐式引用转换。


这看起来像是一个catch-22。 有没有一种方法可以定义参数来表明它必须同时实现BaseClass和IInterface?

解决方案



我只需要重新定义类就可以了:

  public class MyClass< T> T:BaseClass,IInterface 
{
public MyClass(T value)
{
Register(value);
}
}


I'm trying to call a method with a definition similar to the following (simplified to avoid confusion):

public static void Register<T>(T value) where T : BaseClass, IInterface

This works fine so long as I have a class instance that defines both of those values. The problem occurs when I pass a `BaseClass' into a method and then try to use that instance in the above declaration. For example:

public class MyClass
{
    public MyClass(BaseClass value)
    {
        Register(value);
    }
}

I can pass and instance of a class that implements both BaseClass and IInterface into the constructor, but when I try to use that value in the Register method I get a compilation error stating:

The type 'BaseClass' cannot be used as type parameter 'T' in the generic type or method 'Register(T)'. There is no implicit reference conversion from 'BaseClass' to 'IInterface'.

If I change the type in the constructor like so:

public class MyClass
{
    public MyClass(IInterface value)
    {
        Register(value);
    }
}

I get an error stating:

The type 'IInterface' cannot be used as type parameter 'T' in the generic type or method 'Register(T)'. There is no implicit reference conversion from 'IInterface' to 'BaseClass'.

This seems like a bit of a catch-22. Is there a way that I can define the parameter to indicate that it must implement both BaseClass and IInterface?

解决方案

As I was writing the question I came up with the answer and thought I would post it instead of deleting the question.

I just need to redefine the class:

public class MyClass<T> where T : BaseClass, IInterface
{
    public MyClass(T value)
    {
        Register(value);
    }
}

这篇关于一般有多个约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆