2
我對C#和.NET相當新 - 我試圖讓轉換工作從一個整數到一個枚舉。轉換必須由ChangeType執行(在我的演示之外,因爲它在數據綁定框架內,所以它是固定的),並且從我讀過的內容中應該能夠處理我正在做的事情,但是我得到一個異常,並且如果我將在我的轉換類的功能斷點,沒有任何東西被調用。C#TypeConverter長枚舉類型在更改類型上失敗
在此先感謝! -馬修。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace csharptest
{
class Program
{
[TypeConverter(typeof(UnitEnumConverter))]
public enum LengthUnits
{
METRES,
FEET
};
public class UnitEnumConverter : EnumConverter
{
public UnitEnumConverter(System.Type type)
: base(type.GetType())
{
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(Int64)) return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is Int64)
{
return (LengthUnits)(Int64)value;
}
return base.ConvertFrom(context, culture, value);
}
}
static void Main(string[] args)
{
LengthUnits units = new LengthUnits();
long x = 1;
units = (LengthUnits)System.Convert.ChangeType(x, typeof(LengthUnits));
}
}
}
謝謝 - 我已經修改了,但不幸的是我仍然在最後(代碼)行上得到InvalidCastException :-( – 2009-09-04 12:11:13
更新了答案,我只看了TypeConverter問題,我沒有看過 – 2009-09-04 12:55:41
Mike,再次感謝您的幫助。不幸的是,我無法控制轉換是如何完成的。我有一個數據庫,其中包含一個字段,其中包含一個字段我的枚舉值的數值表示(Int64)被數據綁定到LengthUnits類型的屬性 如果我什麼都不做,它根本不起作用,如果我向綁定添加一個Format處理程序,那麼我可以處理這種方式,但必須爲每一個單一的控制(而不是在設計時間)這樣做。 我真正想要的是將數據綁定成功從Int32類型的字段工作到LengthUnits類型的屬性:-s – 2009-09-04 13:14:03