最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Why does Activator.CreateInstance take a CultureInfo argument? - Stack Overflow

programmeradmin5浏览0评论

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 the type constructor. If culture is null, 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 the type constructor. If culture is null, 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?

Share Improve this question asked Apr 1 at 21:23 brads3290brads3290 2,1171 gold badge17 silver badges22 bronze badges 2
  • 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
Add a comment  | 

1 Answer 1

Reset to default 4

The 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)
    }
}
发布评论

评论列表(0)

  1. 暂无评论