C# 如何获取可变属性值?
我的目标是获取类属性及其值 例如,如果我有一个属性“Bindable”来检查属性是否可绑定:C# 如何获取可变属性值?,c#,attributes,C#,Attributes,我的目标是获取类属性及其值 例如,如果我有一个属性“Bindable”来检查属性是否可绑定: public class Bindable : Attribute { public bool IsBindable { get; set; } } 我有个人课: public class Person { [Bindable(IsBindable = true)] public string FirstName { get; set; } [Bindable(IsB
public class Bindable : Attribute
{
public bool IsBindable { get; set; }
}
我有个人课:
public class Person
{
[Bindable(IsBindable = true)]
public string FirstName { get; set; }
[Bindable(IsBindable = false)]
public string LastName { get; set; }
}
如何获取FirstName和LastName的“可绑定”属性值
public void Bind()
{
Person p = new Person();
if (FirstName property is Bindable)
p.FirstName = "";
if (LastName property is Bindable)
p.LastName = "";
}
谢谢。实例没有单独的属性-您必须询问其成员的类型(例如with),并询问这些成员的属性(例如)
编辑:根据评论,有一个关于属性的链接。您可以通过以下方式尝试:
public class Bindable : Attribute
{
public bool IsBindable { get; set; }
}
public class Person
{
[Bindable(IsBindable = true)]
public string FirstName { get; set; }
[Bindable(IsBindable = false)]
public string LastName { get; set; }
}
public class Test
{
public void Bind()
{
Person p = new Person();
foreach (PropertyInfo property in p.GetType().GetProperties())
{
try
{
Bindable _Attribute = (Bindable)property.GetCustomAttributes(typeof(Bindable), false).First();
if (_Attribute.IsBindable)
{
//TODO
}
}
catch (Exception) { }
}
}
}
MSDN上有一个很好的例子来说明这一点。@JonSkeet我有一个变量叫做
string key
,其中的值是profile\u image
,因此,我可以获取键的值
并将其动态设置为属性吗?因为我的方法需要一个类似属性=值
@PrashantPimpale的值:我恐怕不太清楚您想做什么。这可能值得问一个新问题。@JonSkeet这里是一个描述过的问题