简体   繁体   English

自动实现的属性和附加功能

[英]Auto-implemented properties and additional function

Is there a way to do something like this in C#: 有没有一种方法可以在C#中执行以下操作:

public class Class2 {
 public string PropertyName1 { get 
   {
         return this; //i mean "PropertyName1"
   }
   set {
       this = value;
       DoAdditionalFunction();
   }
}

Because I need to call additional function in the "set" I need to have an extra private field like 因为我需要在“集合”中调用其他函数,所以我需要有一个额外的私有字段,例如

private string _propertyName1;
 public string PropertyName1 { get 
   {
         return _propertyName1;
   }
   set {
       _propertyName1= value;
       DoAdditionalFunction();
   }

I don't want to use additional property like _propertyName1. 我不想使用其他属性,如_propertyName1。 Is there a way to accomplish this or any best practices? 有没有办法做到这一点或任何最佳做法?

No - if you need any behaviour other than the most trivial "set a field, return the field value", you need to write "full" properties. 否-如果您需要除最琐碎的“设置字段,返回字段值”以外的任何行为,则需要编写“完整”属性。 Automatically implemented properties are only a shorthand for trivial properties. 自动实现的属性只是琐碎属性的简写。

Note that you haven't really got an "extra" private field, in terms of the actual contents of an object - it's just that you're explicitly declaring the private field instead of letting the compiler do it for you as part of the automatically implemented property. 请注意,就对象的实际内容而言,您实际上并没有真正的“额外”私有字段,只是您明确声明了私有字段,而不是让编译器自动将其作为您的一部分实施财产。

(It's not clear what your first property is trying to do - setting this in a class is invalid, and you can't return this from a property of type string unless you've got a conversion to string...) (尚不清楚您的第一个属性要执行的操作-在类中设置this属性无效,除非您已转换字符串,否则您无法从字符串类型的属性中返回this属性。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM