Ran*_*dom 4 .net c# attributes properties
我有重复代码的问题,并希望知道一种方法来进一步缩短代码.
这就是我的代码目前的样子:
private string _description = null;
public string Description
{
get
{
_description = GetLang(this.TabAccountLangs, "TextAccount");
return _description;
}
set
{
if (object.Equals(value, _description))
return;
SetLang(this.TabAccountLangs, "TextAccount", value);
OnPropertyChanged();
}
}
Run Code Online (Sandbox Code Playgroud)
这个属性和代码可以在一个类和整个项目中的serval类中多次出现,唯一改变的是属性的名称和它自己的支持字段,以及方法调用的参数.
现在我想知道,如果有一种方法可以进一步缩短这段代码,例如:(只是伪代码)
[DoYourSuff(FirstParam=this.TabAccountLangs, SecondParam="TextAccount", ThirdParam=value)]
public string Description { get; set; }
Run Code Online (Sandbox Code Playgroud)
这个例子会使用一个属性,但也许有更好的东西,或者属性是最好的方法.我该如何实现这样的属性?
几个答案似乎值得,但这是另一种选择.
看看Fody.
他们有很多插件,其中一些做类似的事情.如果你找不到你喜欢的那个,你可以修改它来做你的意愿(并将其发回以同时为社区做贡献).
所述的PropertyChanged插件Fody,例如,将改变这些51行的代码:
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
string givenNames;
public string GivenNames
{
get { return givenNames; }
set
{
if (value != givenNames)
{
givenNames = value;
OnPropertyChanged("GivenNames");
OnPropertyChanged("FullName");
}
}
}
string familyName;
public string FamilyName
{
get { return familyName; }
set
{
if (value != familyName)
{
familyName = value;
OnPropertyChanged("FamilyName");
OnPropertyChanged("FullName");
}
}
}
public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}
public virtual void OnPropertyChanged(string propertyName)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Run Code Online (Sandbox Code Playgroud)
至14:
[ImplementPropertyChanged]
public class Person
{
public string GivenNames { get; set; }
public string FamilyName { get; set; }
public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}
}
Run Code Online (Sandbox Code Playgroud)