我有一个这样的课:
public class Document
{
public int DocumentType{get;set;}
[Required]
public string Name{get;set;}
[Required]
public string Name2{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我[Required]在Name和Name2属性上放置数据注释,那么一切正常,如果Name或Name2为空,验证将引发错误.
但我希望Name只有当字段DocumentType等于1 Name2时才需要字段,只有当DocumentType等于2 时才需要字段.
public class Document
{
public int DocumentType{get;set;}
[Required(Expression<Func<object, bool>>)]
public string Name{get;set;}
[Required(Expression<Func<object, bool>>)]
public string Name2{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
但我知道我不能,它会导致错误.我该怎么做才能满足这个要求?
我正在尝试使用反射在运行时比较两个对象,以使用以下方法循环其属性:
Private Sub CompareObjects(obj1 As Object, obj2 As Object)
Dim objType1 As Type = obj1.GetType()
Dim propertyInfo = objType1.GetProperties
For Each prop As PropertyInfo In propertyInfo
If prop.GetValue(obj1).Equals(prop.GetValue(obj2)) Then
'Log difference here
End If
Next
End Sub
Run Code Online (Sandbox Code Playgroud)
每当我测试这个方法时,我会在调用prop.GetValue(obj1)时从System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck中获取参数计数不匹配异常.
无论obj1和obj2的类型,还是prop中的类型(在我的测试用例中,第一个属性是布尔值)都会发生这种情况.
我做错了什么以及如何修复它以便我可以比较两个对象的值?
解
我在for循环中添加了以下几行:
Dim paramInfo = prop.GetIndexParameters
If paramInfo.Count > 0 Then Continue For
Run Code Online (Sandbox Code Playgroud)
第一个属性是一个参数,这导致了问题.现在,我将跳过任何需要参数的属性.
我写了一个接受泛型参数然后打印其属性的方法.我用它来测试我的网络服务.它正在工作,但我想添加一些我不知道如何实现的功能.我想打印列表的值,因为它现在只写了预期的System.Collection.Generic.List1.
这是我到目前为止的代码,这适用于基本类型(int,double等):
static void printReturnedProperties<T>(T Object)
{
PropertyInfo[] propertyInfos = null;
propertyInfos = Object.GetType().GetProperties();
foreach (var item in propertyInfos)
Console.WriteLine(item.Name + ": " + item.GetValue(Object).ToString());
}
Run Code Online (Sandbox Code Playgroud)