Fra*_*nva 2 c# entity-framework-core .net-core
我有一个用户详细信息类
public partial class UserDetails
{
public int? Level { get; set; }
public string Unit { get; set; }
public string Bio { get; set; }
public bool? Gender { get; set; }
public int? Mobile { get; set; }
public string Photo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我正在编写一个更新方法:
public bool UpdateDetails(string userId, UserProperties updateProperty, string value)
{
switch(updateProperty)
{
case UserProperties.Unit:
details.Unit = value;
break;
case UserProperties.Photo:
details.Photo = value;
break;
default:
throw new Exception("Unknown User Detail property");
}
Run Code Online (Sandbox Code Playgroud)
我可以在 JavaScript 中做一些类似动态属性的事情吗?例如
var details = new UserDetails();
details["Unit"] = value;
Run Code Online (Sandbox Code Playgroud)
更新
截至2019年!试试这个新功能怎么样?! DynamicObject DynamicObject.TrySetMember(SetMemberBinder, Object) 方法
我想弄清楚如何写它。
您可以通过反射对象上存在的属性来实现。
C# 有一个名为Indexers的功能。您可以像这样扩展您的代码以允许您期望的行为。
public partial class UserDetails
{
public int? Level { get; set; }
public string Unit { get; set; }
public string Bio { get; set; }
public bool? Gender { get; set; }
public int? Mobile { get; set; }
public string Photo { get; set; }
// Define the indexer to allow client code to use [] notation.
public object this[string propertyName]
{
get {
PropertyInfo prop = this.GetType().GetProperty(propertyName);
return prop.GetValue(this);
}
set {
PropertyInfo prop = this.GetType().GetProperty(propertyName);
prop.SetValue(this, value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
除此之外,如果您不知道运行时的属性,则可以使用动态类型。
| 归档时间: |
|
| 查看次数: |
1671 次 |
| 最近记录: |