我希望使用文件中的一些数据初始化我的类的属性。我为类创建了DataSourceAttribute,为属性创建了DataItemAttribute。我还为这些类创建了抽象父类,我想要初始化字段。请参阅以下代码:
[AttributeUsage(AttributeTargets.Class)]
public class DataInitializerAttribute: Attribute
{}
[AttributeUsage(AttributeTargets.Property)]
public class DataItemAttribute: Attribute
{
public string FileName { get; set; }
public string Field { get; set; }
public string Value
{
get { return "someValue"; // here I will read file}
}
public DataItemAttribute(string fileName)
{
FileName = fileName;
}
}
public abstract class PropertyInitializer
{
protected PropertyInitializer()
{
var classAttribute = GetType().GetCustomAttribute<DataInitializerAttribute>();
if (classAttribute == null)
{
return;
}
var properties = GetType().GetProperties();
foreach (var property in properties)
{
var attribute = property.GetCustomAttribute<DataItemAttribute>();
if (attribute == null)
{
continue;
}
property.SetValue(this, attribute.Value);
}
}
}
一切都很好,但也许可以在不继承PropertyInitializer类的情况下实现更优雅的解决方案?