MVC.net c#如何根据对象的运行时值做出决定?
本文关键字:运行时 决定 对象 net 何根 MVC | 更新日期: 2023-09-27 18:12:21
我有以下代码,它接受两个对象并返回一个可能已更改的属性列表:
public static List<ConfirmRow> EnumerateFormDiffs(object dbForm, object webForm)
{
var output = new List<ConfirmRow>();
var type = dbForm.GetType();
PropertyInfo[] propertyInfos = type.GetProperties();
foreach (var property in propertyInfos)
{
Type propertyType = property.GetType();
if (!propertyType.IsPrimitive && !propertyType.Equals(typeof(string)) && !propertyType.Equals(typeof(DateTime)))
{
continue;
}
var oldVal = property.GetValue(dbForm, null);
var newVal = property.GetValue(webForm, null);
if (oldVal != null && newVal != null)
{
if (oldVal.ToString() != newVal.ToString())
{
var displayName = (ModelMetadata.FromStringExpression(property.Name, new ViewDataDictionary(dbForm)).DisplayName ?? property.Name);
var tmp = new ConfirmRow
{
FieldName = displayName,
OldValue = DisplayField(property.Name, type.Name, oldVal),
NewValue = DisplayField(property.Name, type.Name, newVal)
};
output.Add(tmp);
}
}
else if (oldVal == null && newVal != null)
{
var displayName = (ModelMetadata.FromStringExpression(property.Name, new ViewDataDictionary(dbForm)).DisplayName ?? property.Name);
var tmp = new ConfirmRow { FieldName = displayName, OldValue = "", NewValue = DisplayField(property.Name, type.Name, newVal) };
output.Add(tmp);
}
else if (newVal == null && oldVal != null)
{
var displayName = (ModelMetadata.FromStringExpression(property.Name, new ViewDataDictionary(dbForm)).DisplayName ?? property.Name);
var tmp = new ConfirmRow { FieldName = displayName, OldValue = DisplayField(property.Name, type.Name, oldVal), NewValue = "" };
output.Add(tmp);
}
}
return output;
}
和我比较两个"Enrollment"对象:
public class Enrollment
{
public int Id { get; set; }
public int? ClientId { get; set; }
[ForeignKey("ClientId")]
public virtual Client Client { get; set; }
public int Version { get; set; }
.
.
.
public SaveSubmitStatus? SaveSubmitStatus { get; set; }
}
其中SaveSubmitStatus为Enum。
现在,我想告诉我的代码不要看"Client"字段,因为这会导致问题,但我确实希望它看到"SaveSubmitStatus"字段发生了变化。当我调试这个时,两个属性的PropertyType都是"RuntimePropertyInfo"。谁能告诉我如何确定,并包括在我的if语句,看看"SaveSubmitStatus"字段的差异?在调试时,我在对象中找不到任何东西来允许我确定这一点。
要检查是否为空,您可以尝试以下命令
Nullable.GetUnderlyingType(type) != null
或者对于泛型类型,您可以使用类似于下面的
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
//nullable type
}
嗯,我没有找到一个优雅的解决方案,但它将允许我把这个功能提供给我们的客户。
使用property变量和propertyType变量,我感到困惑。在运行时,属性变量仍然知道属性的名称(我认为这被设置为一个通用的"RuntimePropertyInfo"值)。我可以直接使用属性的名称,这将适用于我们的情况,并将正确地泛化。
感谢大家的阅读和帮助。