如何在分配属性时防止get访问器调用set访问器



适用于:.Net、C#、.Net核心

问题描述:

这可能是Edgecase,或者我做错了什么
我正在使用Microsoft文档创建一个具有属性的类。类应该提供一个到active directory的接口。

当我调用get访问器时,该属性可能尚未在我的程序中设置,因此该属性应该从active directory中提取,设置为类并返回。

为了节省资源,我只想在尚未设置属性的情况下提取该属性。问题是Get-Accessor调用Set-Accessor以便在我的程序中设置属性
Set访问器本身然后尝试将";新的";值返回到active directory,尽管我想从active directory进行Readonly操作。

可复制代码:

这就是这样一个属性的例子:

/// <summary>
/// sAMAccountName - the logon name. eg. "musterma1"
/// </summary>
public string LogonName
{
get
{
// if the value is not set,pull it from active directory
LogonName ??= GetProperty("sAMAccountName");// if null, pull value;
return LogonName;
}
set
{
if (value != LogonName)
{
// if the value has changed, push it to active directory
LogonName = value;
SetProperty("sAMAccountName", LogonName);
}
}
}
// further properties here
/// <summary>
/// this function calls the corresponsing active directory function in order 
/// to populate a poperty of the given user
/// </summary>
/// <param name="property">which property to populate</param>
/// <param name="value">what value should the property have?</param>
private void SetProperty(string property, string value)
{
ObjectProperties.SetProperty(property, value, this.DistinguishedName);
}
/// <summary>
/// this function calls the corresponsing active directory function in order 
/// to receive the current users property
/// </summary>
/// <param name="property">which property to poulate</param>
private string GetProperty(string property)
{
return ObjectProperties.AttributeValuesSingleString("property", this.DistinguishedName);
}

我想先检查null,如果属性当前为null,那么只在程序中设置它,不要将它推送到active directory。但是,那么,分配新的属性呢?值不会被推送:

set
{
if (LogonName == null) LogonName = value;
else if (value != LogonName)
{
// if the value has changed, push it to active directory
LogonName = value;
SetProperty("sAMAccountName", LogonName);
}
}

问题:

你知道如何在我的程序中调用get访问器并设置属性而不调用set访问器并立即将属性推回active directory吗?

您应该创建名为_logonName的私有字段,并使用它重写Get\Set。例如:

private string _logonName;
public string LogonName
{
get
{
// if the value is not set,pull it from active directory
_logonName ??= GetProperty("sAMAccountName");// if null, pull value;
return _logonName;
}
set
{
if (value != _logonName)
{
// if the value has changed, push it to active directory
_logonName = value;
SetProperty("sAMAccountName", _logonName);
}
}
}

我个人建议在设置之前不要检查值是否不同。使用代码的代码可以做到这一点,并且调用Set访问器总是会设置一些内容,这是有道理的。

我会把它改写为

public string LogonName
{
get
{
// if the value is not set,pull it from active directory
LogonName ??= GetProperty("sAMAccountName");// if null, pull value;
return LogonName;
}
set
{
// if the value has changed, push it to active directory
LogonName = value;
SetProperty("sAMAccountName", LogonName);
}
}

然后,如果你关心性能,那么在设置之前,只要期望使用代码进行测试。即

if(class.logonName != newName) 
class.logonName = newName;

这也使得意外引起堆叠式气流更加困难。

最新更新