C#:解决方法非恒定值设置为一个属性? [英] c#: workaround for setting non-constant value to an attribute?
本文介绍了C#:解决方法非恒定值设置为一个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假如我有能力设置为一个System.Object属性说:
Suppose I have an attribute capable to be set to a System.Object say:
[AttributeUsage(AttributeTargets.Property)]
class MyAttrAttribute : Attribute {
public object ThisOne { get; set; }
}
我想获得的这个相同的结果(不编译):
I'd like to get the same result of this (that doesn't compile):
class AttrTarget {
[(MyAttr ThisOne = new MyClass())]
public MyClass Thing { get; set; }
}
有一种方法可以达到同样的效果,而无需使用反射?
There's a way to achieve the same result without using reflection?
问候,贾科莫
推荐答案
默认值
属性,例如具有的 类型,字符串
构造。这可以用来例如创建一个实例对于所需的时间跨度或所需的颜色:
The DefaultValue
attribute for example has a Type, String
constructor. This can be used to create an instance e.g. for desired time span or a desired color:
[DefaultValue(typeof(TimeSpan), "00:00:03")]
public TimeSpan Timeout {get; set;}
[DefaultValue(typeof(Color), "Red")]
public Color HighlightColor {get; set;}
所以,也许这种创造的属性值可以帮助你得到关于如何解决你的问题的想法。
So maybe this kind of creating attribute values helps you to get an idea on how to solve your problem.
这篇关于C#:解决方法非恒定值设置为一个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文