开发者

Is it possible to cast one object into the type of a 2nd object without knowing either type?

I have a simple converter which checks if an object is equal to whatever parameter I pass it. My problem is that the converter parameter always gets passed as string and value always gets passed as object. To compare them properly I need to cast the parameter as the same type as the value. Is there a way I could cast the type of one object to the type of another without knowing either types beforehand?

public class IsObjectEqualParameterConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null && parameter == null)
            return true;

        if (value开发者_JAVA技巧 == null)
            return false;

        // Incorrectly returns False when the ConverterParameter is an integer
        // Would like to try and cast parameter into whatever type value before checking equality
        // Something like: return value.Equals((parameter as value.GetType()));
        return value.Equals(parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

And example usage would be something like:

<Button IsEnabled="{Binding Path=Index, ConverterParameter=0, Converter={StaticResource IsObjectEqualParameterConverter}}" />


parameter = Convert.ChangeType(parameter, value.GetType());

This will only work when the true type of the parameter variable implements IConvertible (all primitive types do, plus string). So it will do string conversions to primitive types:

csharp> Convert.ChangeType("1", typeof(int));
1
csharp> Convert.ChangeType("1", typeof(int)).GetType();
System.Int32

And vice-versa:

csharp> Convert.ChangeType(1, typeof(string));
"1"
csharp> Convert.ChangeType(1, typeof(string)).GetType();
System.String


You can try to use Reflections for this purpose:

using System.Reflection; 
int a = 10;
            string str = "10";
            Type a_type = a.GetType(), str_type = str.GetType();
            try
            {
                if (Convert.ChangeType((object)a, str_type).Equals(str))
                {

                }
            }
            catch (Exception ex)
            {
                //Can't to cast one type to other
            }

If you change types of variables, this code throws exception and notice you that you have tried to cast 'uncastable' types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜