![](/img/trans.png)
[英]How can updating a Canvas attached property also update a bound view model property?
[英]How to update server property on updating client property
我在WCF通信的兩端都有兩個相等的類:
public class UserInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
....
}
一個客戶的班級更新我需要更新服務的班級。 我可以使用以下方法實現WCF服務:
public interface IUserInfoUpdateContract
{
void UpdateFirstName(string value);
void UpdateLastName(string value);
void UpdateAge(string value);
...
}
但是,還有其他方法可以動態更新屬性嗎? 例如:
public interface IUserInfoUpdate
{
void UpdateProperty(string propertyName, object propertyValue);
}
客戶端使用情況:
public class UserInfo
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
wcfClient.UpdateProperty(nameof(FirstName), FirstName);
}
}
}
我有什么選擇可以在沒有反射的情況下動態更新服務端的屬性?
由於您不想使用反射,因此可以執行以下操作。 向UserInfo
添加內部Dictionary
可以保存所有屬性值,然后可以通過屬性名稱string
引用這些值
public class UserInfo
{
private IDictionary<string, object> _dictionary = new Dictionary<string, object>();
public string FirstName
{
get
{
object value;
return _dictionary.TryGetValue(nameof(FirstName), out value) ? (string)value : null;
}
set
{
_dictionary[nameof(FirstName)] = value;
}
}
public string LastName
{
get
{
object value;
return _dictionary.TryGetValue(nameof(LastName), out value) ? (string)value : null;
}
set
{
_dictionary[nameof(LastName)] = value;
}
}
public int Age
{
get
{
object value;
return _dictionary.TryGetValue(nameof(Age), out value) ? (int)value : 0;
}
set
{
_dictionary[nameof(Age)] = value;
}
}
public object this[string property]
{
set
{
//todo: validation if needed
_dictionary[property] = value;
}
}
用法
var info = new UserInfo();
info.FirstName = "hello";
info["LastName"] = "Last";
如果您只想應用UserInfo而不是任何類型,則可以使用if,否則在服務器端只需要一種方法。
public void UpdateProperty(string propertyName,object propertyValue)
{
UserInfo userInfo = new UserInfo(); // use your userInfo
if(propertyName == "FirstName")
{
userInfo.FirstName = propertyValue as string;
}
if(propertyName == "Age")
{
userInfo.Age = (int)propertyValue;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.