使用 PropertyInfo 将值分配给具有自定义索引器的包装类
我需要通过 PropertyInfo 分配一个值。
当属性的类型是我的自定义类(字典的包装器,旨在包含同一文本的多种语言版本)时,我遇到了一些问题。
看起来像这样:
public class MultilingualString
{
Dictionary<string, string> Versions;
public string this[string languageCode]
{
get
{
if (Versions.Keys.Contains(languageCode))
{
return Versions[languageCode];
}
return null;
}
set
{
if (Versions.Keys.Contains(languageCode))
{
Versions[languageCode] = value;
}
else
{
Versions.Add(languageCode, value);
}
}
// [blah blah other stuff...]
}
所以;现在我有了这个 PropertyInfo 对象 - 以及一个我想用默认语言代码分配的字符串值。
certainPropertyInfo.SetValue(
instance, // an instance of some class exposing a MultilingualString type property
someString,
new[] { "eng" }); // some default language code
这会引发异常。
我猜想 SetValue 的最后一个参数是一个集合索引,它不适用于自定义索引器。
实际上,我想做的显然是:
instance.msProperty["eng"] = someString;
但我只得到了 msProperty 的名称,这就是我使用反射的原因。
到目前为止,我已经考虑过实现一个隐式运算符(在 MultilingualString 类中),允许将字符串值转换为 MultilingualString...但我可以看到该方法的一些问题,例如。这个静态运算符几乎没有办法“知道”默认语言代码是什么。
我可以通过反思实现我的目标吗?
I need to assign a value via PropertyInfo.
I'm having some problems when the type of the property is my custom class (a wrapper around a dictionary, designed to contain multiple language versions of the same text).
It looks like that:
public class MultilingualString
{
Dictionary<string, string> Versions;
public string this[string languageCode]
{
get
{
if (Versions.Keys.Contains(languageCode))
{
return Versions[languageCode];
}
return null;
}
set
{
if (Versions.Keys.Contains(languageCode))
{
Versions[languageCode] = value;
}
else
{
Versions.Add(languageCode, value);
}
}
// [blah blah other stuff...]
}
So; now I have this PropertyInfo object - and a string value I would like to assign with a default language code.
certainPropertyInfo.SetValue(
instance, // an instance of some class exposing a MultilingualString type property
someString,
new[] { "eng" }); // some default language code
This throws an exception.
I guess the last argument of SetValue is meant to be a collection index and it doesn't work with a custom indexer.
Effectively what I'm trying to do is, obviously:
instance.msProperty["eng"] = someString;
But I am only given the name of msProperty, that's why I'm using reflection.
So far I have thought about implementing an implicit operator (within the MultilingualString class), allowing to convert string values to MultilingualString... but I can see some problems with that approach eg. this static operator would hardly have a way of "knowing" what the default language code is.
Can I achieve my goal via reflection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
索引器是它自己的属性。您需要在您的某个属性中获取实例的索引器属性:
Item
是索引器属性的默认名称。如果您使用的是 .NET 4.0,则可以使用新的
dynamic
类型:The indexer is a property of its own. You need to get the indexer property of the instance in that certain property of yours:
Item
is the default name for the indexer property.If you are using .NET 4.0, you can use the new
dynamic
type: