是否可以在不知道任何类型的情况下将一个对象转换为第二个对象的类型?

Rac*_*hel 1 c# wpf converter

我有一个简单的转换器,它检查一个对象是否等于我传递它的任何参数.我的问题是转换器参数总是作为字符串传递,值总是作为对象传递.为了正确地比较它们,我需要将参数转换为与值相同的类型.有没有办法在不事先知道任何一种类型的情况下将一个对象的类型转换为另一个对象的类型?

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

        if (value == 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

示例用法如下:

<Button IsEnabled="{Binding Path=Index, ConverterParameter=0, Converter={StaticResource IsObjectEqualParameterConverter}}" />
Run Code Online (Sandbox Code Playgroud)

cdh*_*wie 6

parameter = Convert.ChangeType(parameter, value.GetType());
Run Code Online (Sandbox Code Playgroud)

这仅在parameter变量的真实类型实现时才起作用IConvertible(所有基本类型都是,加上字符串).所以它会对原始类型进行字符串转换:

csharp> Convert.ChangeType("1", typeof(int));
1
csharp> Convert.ChangeType("1", typeof(int)).GetType();
System.Int32
Run Code Online (Sandbox Code Playgroud)

反之亦然:

csharp> Convert.ChangeType(1, typeof(string));
"1"
csharp> Convert.ChangeType(1, typeof(string)).GetType();
System.String
Run Code Online (Sandbox Code Playgroud)