我有这个属性:
\n\n [DisplayName("Conexi\xc3\xb3n")]\n [TypeConverter(typeof(Converters.DevicesTypeConverter))]\n [Description("Conexi\xc3\xb3n con el dispositivo a usar.")]\n [Required]\n public string Conexion { get; set; }\nRun Code Online (Sandbox Code Playgroud)\n\n我需要获取它的类型转换器实例。我尝试过:
\n\n PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(this);\n PropertyDescriptor property = properties.Find("Conexion", false);\n var converter = TypeDescriptor.GetConverter(property);\nRun Code Online (Sandbox Code Playgroud)\n\n甚至还有:
\n\n PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(this);\n PropertyDescriptor property = properties.Find("Conexion", false);\n var converter = TypeDescriptor.GetConverter(property.PropertyType);\nRun Code Online (Sandbox Code Playgroud)\n\n这样,我只能得到属性类型的转换器,即字符串类型的转换器,而不是实际的属性转换器DevicesTypeConverter。
\n\n有什么帮助吗?
\n\n编辑:
\n\n我正在尝试做的事情如下。我在类中有 2 个属性需要通过属性网格来设置。
\n\n“Conexion”属性是依赖于其他属性的值列表。
\n\n这种依赖关系以这种方式运作良好:
\n\n当其他属性发生更改,然后我展开“Conexion”属性时,将调用“Conexion”上的 GetStandardValuesSupported 方法。在该方法中,我使用“context.Instance”来调用对象实例上的方法,该方法以这种方式检索列表:
\n\n public List<object> GetDevicesList()\n {\n if (this.Driver == null)\n return null;\n\n var devices = this.Driver.GetList();\n\n if (devices == null)\n return null;\n\n return devices.Select(l => (object)l.Value).ToList();\n }\nRun Code Online (Sandbox Code Playgroud)\n\n返回的列表存储在转换器中的私有变量中,因此这完美地显示了依赖于其他属性的列表。
\n\n到目前为止,一切都很好。当对象的属性已经具有值时,就会出现问题。由于“Conexion”列表是排他的,因此当我将其分配给属性网格时,它的属性值显示为空。
\n\n这是显而易见的,因为仅在调用 GetStandardValuesSupported 时才会填充依赖列表,并且仅在我尝试编辑属性时才会发生这种情况。
\n\n现在我需要我在问题中提出的问题。我需要在对象构造函数中显式调用 GetStandardValuesSupported,以便在分配“Conexion”属性之前强制加载依赖列表。这样,我确信该属性将显示为已初始化,因为列表将具有其值。
\n\n我认为你的解决方案应该有效,但 GetConverter 返回 null。问题只是减少为调用自定义类型转换器的 GetStandardValuesSupported(),因此我也可以使用 Activator.CreateInstance,但问题是转换器的类型为 null,而不是 DevicesTypeConverter 的类型。
\n您必须跳过几层才能获取(LINQPad demoTypeConverter )中指定的实例:TypeConverterAttribute
//Get the type you are interested in.
var type = typeof(MyClass);
//Get information about the property you are interested in on the type.
var prop = type.GetProperty("Conexion");
//Pull off the TypeConverterAttribute.
var attr = prop.GetCustomAttribute<TypeConverterAttribute>();
//The attribute only stores the name of the TypeConverter as a string.
var converterTypeName = attr.ConverterTypeName;
// Get the actual Type of the TypeConverter from the string.
var converterType = Type.GetType(converterTypeName);
//Create an instance of the TypeConverter.
var converter = (TypeConverter) Activator.CreateInstance(converterType);
Run Code Online (Sandbox Code Playgroud)
既然您已经有了类型,您就可以使用现有的方法来获取转换器:
var converter = TypeDescriptor.GetConverter(converterType);
Run Code Online (Sandbox Code Playgroud)