首页 > 解决方案 > 具有接口和类的类型参数的多重约束

问题描述

void Add<TEntity>(TEntity entity) where TEntity : class, ISpecificEntity; 只想使用特定接口的类。

那有什么意义呢?我可以用 void Add<TEntity>(TEntity entity) where TEntity : ISpecificEntity;

但我不想实现结构。我只想使用一些接口的类。

是的。我可以删除类。但是如何不实现结构呢?

标签: c#

解决方案


在您的示例class, 中,实际上实现的是它使传递值类型变得更加困难(但并非不可能)。

下面是一个例子。有了class约束,(ISpecificEntity)需求就在那里。没有class约束,(ISpecificEntity)不需要在那里。

class不允许传入 s是一个常见的误解struct。这是不正确的。它基本上意味着“这种类型必须是类或接口”。

如果您确实必须禁止值类型,则需要检查方法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);
        }
    }
}

推荐阅读