c# - 具有接口和类的类型参数的多重约束
问题描述
我 void Add<TEntity>(TEntity entity) where TEntity : class, ISpecificEntity;
只想使用特定接口的类。
那有什么意义呢?我可以用 void Add<TEntity>(TEntity entity) where TEntity : ISpecificEntity;
但我不想实现结构。我只想使用一些接口的类。
是的。我可以删除类。但是如何不实现结构呢?
解决方案
在您的示例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);
}
}
}
推荐阅读
- javascript - 一次只有一个按钮处于活动状态,具体取决于状态
- maven - withMaven UNSTABLE 构建结果未保存在 Jenkins 声明性管道中
- javascript - ENOENT:没有这样的文件或目录 preview.vue、prismic 模块和 nuxt-i18n
- c# - 是否可以简化 trycatch 块?
- c - 在C中通过引用定义数组元素
- python - 从 19.2.3 升级到 20.0 后 pip 命令不起作用
- reactjs - ReactJS:将对象作为参数发送给函数,字段未定义
- javascript - 获取所选文本框的计数 indesign
- python - 没有名为 tensorflow.contrib 的模块
- r - 在 R 中找到某一年的最接近值