使用反射 Invoke 时设置 CultureInfo
我正在开发一个类型转换器,它在目标类型上查找 Parse 方法。发现没有问题并且调用得很好。问题是当将特定的 CultureInfo
传递给 Invoke
方法时,它没有任何效果。
演示代码:
const BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
var parser = typeof(decimal).GetMethod("Parse", flags, null, new[] { typeof(string) }, null);
var result1 = parser.Invoke(null, flags, null, new[] { "123,456" }, CultureInfo.GetCultureInfo("sv-SE"));
var result2 = parser.Invoke(null, flags, null, new[] { "123,456" }, CultureInfo.GetCultureInfo("en-US"));
Console.WriteLine(result1);
Console.WriteLine(result2);
结果(使用瑞典语语言环境):123,456
123,456
因此,发生的情况是 Parse
方法正在工作,但我传递给 Invoke
的 CultureInfo
被忽略。瑞典调用应将逗号识别为小数,美国调用应将逗号识别为千位分隔符。
Invoke
的 CultureInfo
参数应该做什么? MSDN 说
用于管理类型强制的 CultureInfo 实例。如果为 null,则使用当前线程的 CultureInfo。 (例如,这对于将表示 1000 的字符串转换为 Double 值是必要的,因为不同的文化对 1000 的表示方式不同。)
这是否与将参数传递给您正在调用的方法而不是操作时的内部转换有关调用期间的 CurrentCulture
?在我继续之前,我只是想弄清楚这一点。我可能需要找到包含 CultureInfo 参数的 Parse 方法......此时我将放弃这个想法。
I'm working on a type converter that looks for a Parse method on the target type. It is found without a problem and invokes just fine. The problem is when passing specific CultureInfo
to the Invoke
method, it has no effect.
Demo code:
const BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
var parser = typeof(decimal).GetMethod("Parse", flags, null, new[] { typeof(string) }, null);
var result1 = parser.Invoke(null, flags, null, new[] { "123,456" }, CultureInfo.GetCultureInfo("sv-SE"));
var result2 = parser.Invoke(null, flags, null, new[] { "123,456" }, CultureInfo.GetCultureInfo("en-US"));
Console.WriteLine(result1);
Console.WriteLine(result2);
Results (using Swedish locale):123,456
123,456
So what's happening is that the Parse
method is working, but the CultureInfo
I pass to Invoke
is ignored. The Swedish invocation should be recognising the comma as a decimal, and the American invocation should be recognising the comma as a thousands separator.
What is the CultureInfo
parameter of Invoke
suppose to be doing? MSDN says
An instance of CultureInfo used to govern the coercion of types. If this is null, the CultureInfo for the current thread is used. (This is necessary to convert a String that represents 1000 to a Double value, for example, since 1000 is represented differently by different cultures.)
Does this have to do with internal conversion when passing parameters to the method you're invoking rather than manipulating the CurrentCulture
during invocation? I'm just trying to figure this out before I press on here. I may need to find Parse methods that contain a CultureInfo parameter...at which point I will abandon this idea.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的假设是正确的;
CultureInfo
仅在Invoke
中使用,以转换参数。您需要将
CultureInfo
传递给方法本身,而不是Invoke
。Your assumption is correct; the
CultureInfo
is only used withinInvoke
, to convert parameters.You need to pass the
CultureInfo
to the method itself, not toInvoke
.