开发者

Is there a way to tell if the user would prefer metric or imperial without asking in C#?

Right now I'm doing:

bool UseMetricByDefault() {
    return TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalHours >= 0;
}

This works for distinguishing USA from Europe and A开发者_如何学Pythonsia, but it ignores South America.

Is there a better way?


Use the RegionInfo class in the System.Globalization namespace:

bool isMetric = RegionInfo.CurrentRegion.IsMetric;

If you want a specific region, you can use one of the following:

// from a CultureInfo
CultureInfo culture = ...;
RegionInfo r = new RegionInfo(culture.Name);

// from a string
RegionInfo r = new RegionInfo("us");


Part of the problem is that even if you use their RegionInfo, not everyone in a region uses the same system. In the US, scientists often use metric in their research, and here in Canada, its a bit of a mix, since we get a lot of food packaging from the US but we teach our children in metric (but only since recently - my parents still think in imperial).

That being said, you can make a fair guess using the RegionInfo class.


Looks like there's already an implementation in System.Globalization.RegionInfo (regionInfo.IsMetric).

You could use the CultureInfo class which can return the Culture of the operating system you're running on - usually in the format en-US en-GB de-DE etc. Cultures are more often used for translating applications from one language to another depending on the culture of the operating system.

This is all for specified localisation - you may want to read up on some tutorials and articles regarding it (ie here).


It's a property on the RegionInfo class:

// en-US, en-GB, de-DE etc.
string cultureName = CultureInfo.CurrentCulture.Name;
RegionInfo regionInfo = new RegionInfo(cultureName);
Console.WriteLine("You prefer to see {0}", regionInfo.IsMetric ? "metric" : "imperial");


For a "stab in the dark" the RegionInfo information is good enough.

However in practice places like the UK have exceptions. For example:

  • anything traffic related is imperial
  • temperatures for weather are metric, but some people prefer imperial
  • measurements of equipment are metric... mostly

Much depends on the generation you're in and your attitude to change.

So - in practice - provide both, take a guess at a sensible default, but if it's important always allow the user to override the preference, and make sure these changes are remembered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜