我创建了一个Attribute名为的类RelatedPropertyAttribute:
[AttributeUsage(AttributeTargets.Property)]
public class RelatedPropertyAttribute: Attribute
{
public string RelatedProperty { get; private set; }
public RelatedPropertyAttribute(string relatedProperty)
{
RelatedProperty = relatedProperty;
}
}
Run Code Online (Sandbox Code Playgroud)
我用它来表示类中的相关属性.我将如何使用它的示例:
public class MyClass
{
public int EmployeeID { get; set; }
[RelatedProperty("EmployeeID")]
public int EmployeeNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想使用lambda表达式,以便我可以将强类型传递给我的属性的构造函数,而不是"魔术字符串".这样我可以利用编译器类型检查.例如:
public class MyClass
{
public int EmployeeID { get; set; }
[RelatedProperty(x => x.EmployeeID)]
public int EmployeeNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我以为我可以使用以下内容,但编译器不允许这样做:
public RelatedPropertyAttribute<TProperty>(Expression<Func<MyClass, TProperty>> propertyExpression)
{ ... } …Run Code Online (Sandbox Code Playgroud) 为什么decimal不是原始类型?
Console.WriteLine(typeof(decimal).IsPrimitive);
Run Code Online (Sandbox Code Playgroud)
输出false.
它是一种基类型,它是语言规范的一部分,但不是原语.什么原始类型代表decimal框架中的一个?一个int例如具有场m_value型的int.A double有一个m_value类型的领域double.事实并非如此decimal.它似乎是由一堆ints 代表,但我不确定.
为什么它看起来像一个原始类型,表现得像一个原始类型(除了在几种情况下)但不是原始类型?
我最近发现,一个.NET属性只能包含基本类型,字符串,枚举,对象和这些类型的单一参数数组作为讨论在这里.
我需要IDictionary<string, string>通过.NET属性接受,但显然我不能IDictionary<string, string>因为上述原因而使用.所以,我在这里寻找可以在这些指导方针中起作用的替代方案.
// I want to do this, but can't because of the CLR limitation
[MyAttribute(Attributes = new Dictionary { { "visibility", "Condition1" }, { "myAttribute", "some-value" } })]
Run Code Online (Sandbox Code Playgroud)
我提出的两个可能的选项是在声明中使用XML或JSON(作为.NET属性上的字符串),这可以很容易地IDictionary<string, string>为我的应用程序序列化,但是这会将声明变成一个冗长的容易出错的字符串没有语法检查.
// XML
[MyAttribute(Attributes = "<items><item key='visibility' value='Condition1'/><item key='myAttribute' value='some-value'/></items>")]
// JSON
[MyAttribute(Attributes = "{ 'visibility': 'Condition1', 'myAttribute': 'some-value' }")]
Run Code Online (Sandbox Code Playgroud)
如果有的话,还有哪些其他替代方案比这更优雅/更直接?