[英]Add code to C# get/set of property without needing backing field?
You know how you can have a property that automatically generates a backing field?您知道如何拥有自动生成支持字段的属性吗? Like if I go:就像我去:
public String SomeProperty {get; set;}
I know that if I want to add code to that property I have to create the backing field as so:我知道如果我想向该属性添加代码,我必须像这样创建支持字段:
public string someProperty = string.Empty;
public string SomeProperty
{
get { return someProperty; }
set
{
someProperty = value;
DoSomething();
}
}
Basically, what I want to know is... is there any way to do this but without having to create the backing field?基本上,我想知道的是......有没有办法做到这一点,但不必创建支持字段? For example I could use it to trigger some kind of event that occurs when a property is set.例如,我可以使用它来触发某种在设置属性时发生的事件。 I'm looking for something like this:我正在寻找这样的东西:
public string SomeProperty
{
get;
set { this.OnSomeEvent; }
}
But I know that'll cause a compile error because get
needs do declare a body if set
does.但我知道,因为这会导致编译错误get
需要做,如果声明主体, set
一样。
I've researched and I cant find anything, but I thought I'd check to see if anyone knew.我已经研究过,但找不到任何东西,但我想我会检查是否有人知道。
I guess what I'm really after is some way to trigger an event when a property is changed but without having to add all that extra clutter.我想我真正想要的是在更改属性时触发事件的某种方式,但不必添加所有额外的混乱。 Any suggestions?有什么建议么?
There are not any solutions for this built into the framework, and you cannot modify existing types via reflection (in order to add the logic at runtime).框架中没有为此内置任何解决方案,并且您不能通过反射修改现有类型(以便在运行时添加逻辑)。 The only way to accomplish this seems to be at compile time.实现这一点的唯一方法似乎是在编译时。
There is a product http://www.postsharp.net/ that can accomplish this (intercept property/method calls), and there does appear to be a free edition.有一个产品http://www.postsharp.net/可以做到这一点(拦截属性/方法调用),而且似乎有一个免费版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.