admin管理员组文章数量:1350050
Activator.CreateInstance takes a CultureInfo
argument. The docs give the following description for this argument:
Culture-specific information that governs the coercion of
args
to the formal types declared for thetype
constructor. Ifculture
isnull
, the CultureInfo for the current thread is used.
What does this mean? What are some examples of when one culture
would give a different result than a different culture
?
Activator.CreateInstance takes a CultureInfo
argument. The docs give the following description for this argument:
Culture-specific information that governs the coercion of
args
to the formal types declared for thetype
constructor. Ifculture
isnull
, the CultureInfo for the current thread is used.
What does this mean? What are some examples of when one culture
would give a different result than a different culture
?
- 1 DateTime.ToString or most of formatting related stuff – Selvin Commented Apr 1 at 21:42
- 1 Quote: This is necessary to convert a string that represents 1000 to a Double value, for example, since 1000 is represented differently by different cultures – Hans Passant Commented Apr 1 at 22:09
1 Answer
Reset to default 4The CultureInfo
argument in Activator.CreateInstance
is used when converting constructor arguments to the required types, particularly for parsing culture-sensitive data like numbers and dates.
As an example: Different number format. Some cultures use a comma (,
) as a decimal separator, while others use a period (.
). This can affect how numbers are parsed when passed as constructor arguments.
using System;
using System.Globalization;
public class Example
{
public double Value { get; }
public Example(double value)
{
Value = value;
}
}
class Program
{
static void Main()
{
object[] args = { "3,14" }; // String representation of a number
// Using German culture (comma as decimal separator)
var germanCulture = new CultureInfo("de-DE");
var instanceDE = (Example)Activator.CreateInstance(typeof(Example), args, null, germanCulture, null);
Console.WriteLine(instanceDE.Value); // Output: 3.14
// Using US culture (period as decimal separator)
var usCulture = new CultureInfo("en-US");
var instanceUS = (Example)Activator.CreateInstance(typeof(Example), args, null, usCulture, null);
Console.WriteLine(instanceUS.Value); // Throws exception (cannot parse "3,14" as a double)
}
}
本文标签: cWhy does ActivatorCreateInstance take a CultureInfo argumentStack Overflow
版权声明:本文标题:c# - Why does Activator.CreateInstance take a CultureInfo argument? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743870138a2553315.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论