我有几个类,我希望用特定的属性标记.我有两种方法.一个涉及使用属性扩展类.另一个使用空接口:
属性
public class FoodAttribute : Attribute { }
[Food]
public class Pizza { /* ... */ }
[Food]
public class Pancake { /* ... */ }
if (obj.IsDefined(typeof(FoodAttribute), false)) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
接口
public interface IFoodTag { }
public class Pizza : IFoodTag { /* ... */ }
public class Pancake : IFoodTag { /* ... */ }
if (obj is IFoodTag) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
由于使用了Reflection,我对使用这些属性犹豫不决.然而,与此同时,我对创建一个仅用作标记的空接口犹豫不决.我对它们进行了压力测试,两者之间的时间差仅为3毫秒左右,因此这里的性能并未受到影响.
我有两个C#类,它们具有许多相同的属性(按名称和类型).我希望能够将实例中的所有非空值复制Defect到实例中DefectViewModel.我希望用反射来做,使用GetType().GetProperties().我尝试了以下方法:
var defect = new Defect();
var defectViewModel = new DefectViewModel();
PropertyInfo[] defectProperties = defect.GetType().GetProperties();
IEnumerable<string> viewModelPropertyNames =
defectViewModel.GetType().GetProperties().Select(property => property.Name);
IEnumerable<PropertyInfo> propertiesToCopy =
defectProperties.Where(defectProperty =>
viewModelPropertyNames.Contains(defectProperty.Name)
);
foreach (PropertyInfo defectProperty in propertiesToCopy)
{
var defectValue = defectProperty.GetValue(defect, null) as string;
if (null == defectValue)
{
continue;
}
// "System.Reflection.TargetException: Object does not match target type":
defectProperty.SetValue(viewModel, defectValue, null);
}
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?我应该维护单独的Defect属性和DefectViewModel属性列表,以便我可以做到viewModelProperty.SetValue(viewModel, defectValue, null)吗?