![](/img/trans.png)
[英]C# - Faster way to get set public static fields instead of using Reflection.SetValue / GetValue
[英]How to provide conversion when using Reflection.SetValue?
我有一個假裝為int的類,因此它使各種運算符都超負荷了。
public class MyId
{
int value;
public virtual int Value
{
get { return this.value; }
set { this.value = value; }
}
public MyId(int value)
{
this.value = value;
}
public static implicit operator MyId(int rhs)
{
return new MyId(rhs);
}
public static implicit operator int(MyId rhs)
{
return rhs.Value;
}
}
但是,當我使用類似
PropertyInfo.SetValue(myObj, 13, null)
OR
MyId myId = 13;
int x = Convert.ToInt32(myId);
IConvertible iConvertible = x as IConvertible;
iConvertible.ToType(typeof(MyId), CultureInfo.CurrentCulture);
我得到無效的演員表。 我很困惑,這兩個調用似乎都試圖在int上調用convert,這將失敗,因為int無法理解MyId類型(即使所有賦值運算符都在那里)。 任何解決方法的想法,我確定我一定會丟失一些愚蠢的東西嗎?
隱式轉換是C#構造,無法通過反射獲得。 此外,通過反射設置字段或屬性意味着您必須預先提供適當的類型。 您可以嘗試通過使用自定義TypeConverter(或某些其他自定義轉換方法)來規避此問題,以幫助在使用反射之前在運行時轉換類型。 這是TypeConverter實現的一個粗略示例。
public class MyIdTypeConverter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value)
{
if (value is int)
return new MyId((int)value);
else if (value is MyId)
return value;
return base.ConvertFrom(context, culture, value);
}
}
這是我們嘗試設置Custom
屬性的類型。
public class Container
{
[TypeConverter(typeof(MyIdTypeConverter))]
public MyId Custom { get; set; }
}
調用它的代碼必須檢查屬性並提前執行轉換,然后才能調用SetValue
。
var instance = new Container();
var type = typeof(Container);
var property = type.GetProperty("Custom");
var descriptor = TypeDescriptor.GetProperties(instance)["Custom"];
var converter = descriptor.Converter;
property.SetValue(instance, converter.ConvertFrom(15), null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.