1

可以创建一个行为类似于CallerMemberNameAttribute?

我的意思是,我用谷歌搜索并找到了这篇文章,它说 CallerMemberName 是属于 CompilerServices 组的属性,或者换句话说,这个属性改变了编译器构建我的 IL 的方式。因此,如果不自定义 c# 编译器,就不可能复制这种行为。

但我还不相信。我希望stackoverflow中的某个人可以另说。所以这个问题是给它的。

一些上下文:

我正在寻找这个主要是为了改进这个代码:

public int Prop
{
    { get { return (int)this["prop"]; }
    { set { this["prop"] = value; }
}

我的应用程序中有许多类是字典,并且具有表示特定键的属性。

使用StackTrace(在 C# 4.0 中)和CallerMemberName(在 C# 5.0 中)我能够将我的代码更新为:

public int Prop
{
    { get { return Get(); }
    { set { Set(value); }
}

现在我的目标是归档一些这样的:

public int Prop { { [DicGet]get; [DicSet]set; } }

那么有人可以帮助我吗?这是可能的?

4

1 回答 1

2

It is possible to create an attribute that has a behavior similar to CallerMemberNameAttribute?

Only by changing the C# compiler yourself, basically. After all, you're asking for behaviour similar to something that the C# compiler has specific knowledge of and code to handle - so you should expect that the C# compiler would need specific knowledge and code to handle your similar situation.

Now my goal is to archive some like this:

public int Prop { { [DicGet]get; [DicSet]set; } }

So can someone help me? It's possible?

Not out of the box, no.

Options:

  • Modify the Roslyn compiler (it's open source now) - I wouldn't recommend that though.
  • Use PostSharp
  • Use some sort of preprocessor before you compile
  • Use dynamic typing instead (e.g. extend DynamicObject and handle property accesses that way)
于 2015-04-02T13:36:58.150 回答