Attribute
というクラスを作成しましたRelatedPropertyAttribute
:
[AttributeUsage(AttributeTargets.Property)]
public class RelatedPropertyAttribute: Attribute
{
public string RelatedProperty { get; private set; }
public RelatedPropertyAttribute(string relatedProperty)
{
RelatedProperty = relatedProperty;
}
}
これを使用して、クラス内の関連するプロパティを示します。私がそれを使用する方法の例:
public class MyClass
{
public int EmployeeID { get; set; }
[RelatedProperty("EmployeeID")]
public int EmployeeNumber { get; set; }
}
「魔法の文字列」ではなく、強力な型を属性のコンストラクターに渡すことができるように、ラムダ式を使用したいと思います。このようにして、コンパイラの型チェックを利用できます。例えば:
public class MyClass
{
public int EmployeeID { get; set; }
[RelatedProperty(x => x.EmployeeID)]
public int EmployeeNumber { get; set; }
}
次のようにできると思っていましたが、コンパイラで許可されていません。
public RelatedPropertyAttribute<TProperty>(Expression<Func<MyClass, TProperty>> propertyExpression)
{ ... }
エラー:
非ジェネリック型 'RelatedPropertyAttribute' は型引数では使用できません
どうすればこれを達成できますか?