开发者

Is there a good way to get the current property name?

开发者 https://www.devze.com 2023-02-23 15:27 出处:网络
I know there are ways, but is there actually a good way? At the moment I have a decent Attribute based framework which is working really well with the exception of the verbosity of:

I know there are ways, but is there actually a good way?

At the moment I have a decent Attribute based framework which is working really well with the exception of the verbosity of:

public Variable<int> Value { get { return Get.Int(MethodBase.CurrentMethod()); } }

Picture that, * a few hundred (with setters often too). Is there anyway to get the same result but more concise?

I've considered:

public Variable<int> Value { get { return Get.Int("Value"); } }

and tried:

public Variable<int> Value { get { return Get.Int(() => Value); } }

But as there's many, many of these variables (there is method in this madness, I promise) I'm concerned about obscure bugs arising from the second Value (or string) not matching the first.

So my question is, can anyone think of a neater way to write the above? All I need is the current property name.

My favourite "solution" so far has been:

protected Func<MethodBase> Self = MethodBase.GetCurrentMethod;
publ开发者_高级运维ic Variable<int> Value { get { return Get.Int(Self()); } }

Which is short, sweet, and pretty to look at.

But alas the JIT kills rules that out as an option. Is there perhaps a way I can rewrite GetCurrentMethod in C#, under a different name? It's a pity StackCrawlMark (which I believe is required) is internal to System.

Alternatively, are there any tools out there that are compatible with ReSharper but perhaps let me view the code through goggles, reducing the verbose MethodBase.GetCurrentMethod to something shorter and sweeter, whilst still compiling exactly the same? (I'd really rather not have a pre-compile fiddling step, but am open to suggestions - one that reduced it all to the property name would be nice).


In short, no. There are various attempts at this, including stack inspection (GetCurrentMethod) and lambda expressions, but ultimately they are all a bit inefficient.

Unless you need need obfuscation, I would just use a string - Get.Int("Value") - this is very unlikely to be a genuine maintenance problem.

The stack inspection approach suffers from potential brittleness if it inlines; if you need obfuscation, I would probably go with Expression. Or just mark the method as "don't obfuscate this name".

Another approach would be to have an abstract base type, and use meta-programming to create the concrete type with the right data/code at runtime, based on inspecting your attributes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号