简体   繁体   English

带有接口和 class 的类型参数的多重约束

[英]Multiple constraints on type parameters with interface and class

I have void Add<TEntity>(TEntity entity) where TEntity: class, ISpecificEntity;我有void Add<TEntity>(TEntity entity) where TEntity: class, ISpecificEntity; I just want use class of specific interface.我只想使用特定接口的 class 。

what the point of that?那有什么意义呢? I can use void Add<TEntity>(TEntity entity) where TEntity: ISpecificEntity;我可以使用void Add<TEntity>(TEntity entity) where TEntity: ISpecificEntity;

But I do not want to implement structure.但我不想实现结构。 I just want use class of some interface.我只想使用某些接口的 class 。

Yes.是的。 I can remove class.我可以删除 class。 But how not to implement structure?但是如何不实现结构呢?

What class, in practice achieves in your example is it makes it harder (but not impossible) to pass in value types. class,在您的示例中实际上实现的是它使传递值类型变得更加困难(但并非不可能)。

An example is below.下面是一个例子。 With the class constraint, the (ISpecificEntity) needs to be there.使用class约束, (ISpecificEntity)需要在那里。 Without the class constraint the (ISpecificEntity) does not need to be there.如果没有class约束,则(ISpecificEntity)不需要存在。

It is a common misconception that class does not allow struct s to be passed in. This is not true.一个常见的误解是class不允许传入struct 。这是不正确的。 It basically means "this type must be a class or an interface ".它基本上意味着“这种类型必须是 class或接口”。

If you really must disallow value types, you will need to check the value of entity.GetType().IsValueType inside the method (ie at runtime).如果您确实必须禁止值类型,则需要检查方法entity.GetType().IsValueType的值(即在运行时)。

using System;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    public class Bob
    {
        public void Add<TEntity>(TEntity entity) where TEntity : class, ISpecificEntity
        {
            Console.WriteLine(entity.GetType().IsValueType);
            Console.WriteLine("added");
        }
    }

    public interface ISpecificEntity
    {

    }

    public struct SpecificEntity : ISpecificEntity
    {

    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var entity = new SpecificEntity();

            var bob = new Bob();

            bob.Add((ISpecificEntity)entity);
        }
    }
}

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

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