是否可以从属性本身内部获取属性的值? 例如:
public class TestModel
{
[TestAttribute(Value="TestValue")]
public TestClass TestProperty { get; set; }
[TestAttribute(Value="AnotherValue")]
public TestClass AnotherTestProperty { get; set; }
}
public class TestClass
{
public string ReturnSomething()
{
// Get 'TestValue' or 'AnotherValue'
// from 'TestAttribute' here depending on
// which property ReturnSomething() is called on
}
}
修改:澄清一下。我试图实现这一点,而不传递对父项的任何引用,或任何表示属性名称的字符串到ReturnSomething
方法。
答案 0 :(得分:-1)
这对我有用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DemoApp
{
class Program
{
static void Main(string[] args)
{
TestClass testClass = new TestClass();
Console.WriteLine("Return-Value: " + testClass.ReturnSomething("TestProperty", typeof(TestModel)));
Console.WriteLine("Return-Value: " + testClass.ReturnSomething("AnotherTestProperty", typeof(TestModel)));
Console.ReadLine();
}
}
public class TestAttribute : Attribute
{
public string Value
{
get;
set;
}
}
public class TestModel
{
[TestAttribute(Value = "TestValue")]
public TestClass TestProperty { get; set; }
[TestAttribute(Value = "AnotherValue")]
public TestClass AnotherTestProperty { get; set; }
}
public class TestClass
{
public string ReturnSomething(string propertyName, Type modelType)
{
string returnValue = "";
foreach (var property in modelType.GetProperties())
{
if (property.Name == propertyName)
{
// Find Attributes
Attribute[] cAttributes = property.GetCustomAttributes(true).OfType<Attribute>().ToArray();
if (cAttributes != null)
{
// Iterate throught all attributes
foreach (System.Attribute cAttribute in cAttributes)
{
if (cAttribute is TestAttribute)
{
returnValue = (cAttribute as TestAttribute).Value;
break; // Break after first
}
}
}
}
}
return returnValue;
}
}
}
答案 1 :(得分:-1)
是的,可以使用.net反射获取属性本身内属性的属性。要做到这一点,你必须充实属性的getter代码,而不是使用自动属性。
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
class TestAttribute : Attribute
{
public string Value { get; set; }
}
[Test(Value = "Hello")]
public string MyTestProperty
{
get
{
var typeInfo = GetType();
// Get the PropertyInfo descriptor for this property
var propInfo = typeInfo.GetProperty("MyTestProperty");
// Get custom attributes applied to the property
var attr = propInfo.GetCustomAttributes(false).OfType<TestAttribute>().FirstOrDefault();
// If we have an attribute, then return its Value
return attr != null ? attr.Value : "No Attribute";
}
}