是否有可能使用基于属性,而不是类型的泛型约束? [英] Is it possible to use generic constraints based on attributes rather than types?
问题描述
我试着写一个类,将负责持续的应用选择。由于选项必须坚持认为,我送必须serialisable的值。
I'm trying to write a class that will be in charge of persisting application options. Since the options need to be persisted the values that I'm sent must be serialisable.
起初,我以为我已经能够与这样的签名写一个方法:
Initially I thought I've be able to write a method with a signature like this:
Public Sub SaveOption(Of T As ISerializable)(ByVal id As String, ByVal value As T)
如果你preFER C#:
or if you prefer C#:
public void SaveOption<T>(string id, T value) where T : ISerializable
在原则上,这将是罚款,但对于具有&LT类型,序列化&GT;
属性?这方面最明显的例子是System.String,它不执行 ISerializable的
,但显然这是一个类型,我应该能够保存。
In principle this would be fine, but what about types that have the <Serializable>
attribute? The most notable example of this is System.String, it does not implement ISerializable
, but clearly it is a type that I should be able to save.
那么,有没有我可以限制哪些类型允许进入的方法,在编译时,根据其属性的方式?
So, is there a way that I can restrict which types are allowed into a method at compiletime, based on their attributes?
推荐答案
您可以有重载的其他类型 - 把你的字符串例如:
You could have overloads for the other types - taking your string example:
public void SaveOption(string id, string value)
不过,串行化是...棘手;我希望你将不得不在运行时进行检查。
However; serializability is... tricky; I expect you're going to have to check this at runtime.
这篇关于是否有可能使用基于属性,而不是类型的泛型约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!