给定一个自定义属性,我想获取其目标的名称:
public class Example
{
[Woop] ////// basically I want to get "Size" datamember name from the attribute
public float Size;
}
public class Tester
{
public static void Main()
{
Type type = typeof(Example);
object[] attributes = type.GetCustomAttributes(typeof(WoopAttribute), false);
foreach (var attribute in attributes)
{
// I have the attribute, but what is the name of it's target? (Example.Size)
attribute.GetTargetName(); //??
}
}
}
希望一切都清楚!
最佳答案
反过来做:
迭代
MemberInfo[] members = type.GetMembers();
和请求
Object[] myAttributes = members[i].GetCustomAttributes(true);
或
foreach(MemberInfo member in type.GetMembers()) {
Object[] myAttributes = member.GetCustomAttributes(typeof(WoopAttribute),true);
if(myAttributes.Length > 0)
{
MemberInfo woopmember = member; //<--- gotcha
}
}
但使用 Linq 会更好:
var members = from member in type.GetMembers()
from attribute in member.GetCustomAttributes(typeof(WoopAttribute),true)
select member;
关于C# 获取自定义属性目标的成员信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4833734/