我遇到了一个问题,其中我的控件之外的代码类使用的字符串为null,因此当它们被引用例如“string.Length”时,会导致错误。平均而言,使用嵌套类不是为可能的100个字段进行检查,而是认为我可以创建更容易的东西。我有一个想法...PropertyCopy一般地将字符串值从空变为空
如果你已经做了任何研究复制对象PropertyCopy,以及其他一些,是一个非常普遍的发现。我目前使用上面提到的类。我想知道它是否可以修改为简单地去: 如果stringPropertyValue为null,那么设置stringPropertyValue等于string.Empty。
我的理解是有限的。我一直在研究解决我的问题,但没有真正的好主意。我的想法能工作吗?有没有更好的办法?如果可以的话,它会怎么做?
更新:
基于下面我创造了这个类,我目前要使用的回应。
public static void DenullifyStringsToEmpty<T>(this T instance)
{
//handle properties
foreach (var filteredProperties in instance.GetType().GetProperties().Where(p =>
(p.PropertyType.IsClass || p.PropertyType.IsInterface || p.PropertyType == typeof(string))))
{
if (filteredProperties.PropertyType == typeof(string))
{
if (filteredProperties.GetValue(instance, null) == null)
{
filteredProperties.SetValue(instance, string.Empty, null);
}
}
else
{
filteredProperties.GetValue(instance, null).DenullifyStringsToEmpty();
}
}
//handle fields
foreach (var filteredFields in instance.GetType().GetFields().Where(f =>
(f.FieldType.IsClass || f.FieldType.IsInterface || f.FieldType == typeof(string))))
{
if (filteredFields.FieldType == typeof(string))
{
if (filteredFields.GetValue(instance) == null)
{
filteredFields.SetValue(instance, string.Empty);
}
}
else
{
filteredFields.GetValue(instance).DenullifyStringsToEmpty();
}
}
}
我知道反射可能很重,直到我们有一个问题,我觉得这个解决方案将工作的伟大。这是一个扩展(感谢下面的评论)。
感谢您的意见。
每个类有超过100个字段和属性,再加上你使用的代码不在你的控制之下,它不检查空值?我不羡慕你的工作。 – StriplingWarrior 2011-03-31 19:55:44
@StriplingWarrior对于我正在使用的三个当前对象,我的属性数量大约是90/45/60。当我把它们发送出去(或者根据你如何看待它们),初始化值为空,所以代码错误。为了减少编码每一行的头痛......我认为创造性的解决方案是有序的。另外,将来还会有更多(更大)的物体需要处理。我从事有很多小领域的医疗保健工作,以指示不同的事情。 – WaffleTop 2011-03-31 20:19:39