您可以使用"其中"要求在C#中的属性? [英] Can you use "where" to require an attribute in c#?

查看:153
本文介绍了您可以使用"其中"要求在C#中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打只接受序列化的类一个通用类,可以将其与约束在哪里做?

我在寻找的概念是这样的:

 公共类MyClass的< T>其中T:// [可序列化/有Seri​​alizable属性]


解决方案

不,恐怕不行。你可以用约束做的唯一的事情是:


  • ,其中T:类 - T必须是引用类型

  • 其中T:结构 - T必须是一个非空值类型

  • ,其中T:SomeClass的 - T必须是SomeClass的或从中获取

  • ,其中T:ISomeInterface - T必须ISomeInterface或者实现它

  • ,其中T:新的() - T必须有一个公共的无参数构造函数

各种组合是可行的,但不是全部。一无所知的属性。

I want to make a generic class that accepts only serializable classes, can it be done with the where constraint?

The concept I'm looking for is this:

public class MyClass<T> where T : //[is serializable/has the serializable attribute]

解决方案

Nope, I'm afraid not. The only things you can do with constraints are:

  • where T : class - T must be a reference type
  • where T : struct - T must be a non-nullable value type
  • where T : SomeClass - T must be SomeClass or derive from it
  • where T : ISomeInterface - T must be ISomeInterface or implement it
  • where T : new() - T must have a public parameterless constructor

Various combinations are feasible, but not all. Nothing about attributes.

这篇关于您可以使用&QUOT;其中&QUOT;要求在C#中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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