上運行時鑄造我有以下代碼複製屬性值從一個對象到另一個對象通過匹配他們的屬性名稱:使用隱式CON版本
public static void CopyProperties(object source, object target,bool caseSenstive=true)
{
PropertyInfo[] targetProperties = target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
PropertyInfo[] sourceProperties = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo tp in targetProperties)
{
var sourceProperty = sourceProperties.FirstOrDefault(p => p.Name == tp.Name);
if (sourceProperty == null && !caseSenstive)
{
sourceProperty = sourceProperties.FirstOrDefault(p => p.Name.ToUpper() == tp.Name.ToUpper());
}
// If source doesn't have this property, go for next one.
if(sourceProperty ==null)
{
continue;
}
// If target property is not writable then we can not set it;
// If source property is not readable then cannot check it's value
if (!tp.CanWrite || !sourceProperty.CanRead)
{
continue;
}
MethodInfo mget = sourceProperty.GetGetMethod(false);
MethodInfo mset = tp.GetSetMethod(false);
// Get and set methods have to be public
if (mget == null)
{
continue;
}
if (mset == null)
{
continue;
}
var sourcevalue = sourceProperty.GetValue(source, null);
tp.SetValue(target, sourcevalue, null);
}
}
這是工作以及當目標屬性的類型和來源是一樣的。但是當需要投射時,代碼不起作用。
例如,我有以下對象:
class MyDateTime
{
public static implicit operator DateTime?(MyDateTime myDateTime)
{
return myDateTime.DateTime;
}
public static implicit operator DateTime(MyDateTime myDateTime)
{
if (myDateTime.DateTime.HasValue)
{
return myDateTime.DateTime.Value;
}
else
{
return System.DateTime.MinValue;
}
}
public static implicit operator MyDateTime(DateTime? dateTime)
{
return FromDateTime(dateTime);
}
public static implicit operator MyDateTime(DateTime dateTime)
{
return FromDateTime(dateTime);
}
}
如果我這樣做,則隱式轉換被調用,一切正常:
MyDateTime x= DateTime.Now;
但是,當我有兩個對象其中一個具有DateTime,另一個具有MyDateTime,並且我使用上述代碼將屬性從一個對象複製到另一個對象,但不會生成錯誤,表示DateTime無法轉換爲MyTimeDate。
我該如何解決這個問題?
五言中不是一般的情況下,但也許它可以幫助你: http://stackoverflow.com/questions/4501469/c-sharp-implicit-cast-overloading-and-reflection-problem – dvvrd 2012-03-28 16:50:58