有没有办法通过 switch 语句使用字符串资源?尝试以编程方式获取字符串资源后,返回错误。
错误
'resourceLoader' is variable but is used like a type
C#
public class PageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
Type page = null;
switch (value as string)
{
case resourceLoader.GetString("SteveJohnson/Text"):
page = typeof(FirstPage);
break;
case resourceLoader.GetString("PeteDavidson/Text"):
page = typeof(SecondPage);
break;
case resourceLoader.GetString("OneDrive/Text"):
page = typeof(FistPage);
break;
case resourceLoader.GetString("Twitter/Text"):
page = typeof(SecondPage);
break;
default:
break;
}
return page;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
最佳答案
您在寻找 pattern matching ?这只是我最近发现的东西(它是 C# 7 功能 which I came across in this link ),你所做的与我的用例有点不同,但我只是用伪代码运行了一个快速测试(调用一个方法另一个类从 switch
语句获取并返回一个字符串),这似乎有效。对于你正在做的事情,我认为你会有这样的事情:
switch (value)
{
case string _ when (resourceLoader.GetString("SteveJohnson/Text") == value as string):
page = typeof(FistPage);
break;
case string _ when (resourceLoader.GetString("PeteDavidson/Text") == value as string):
page = typeof(SecondPage);
break;
关于c# - 如何在 switch 语句中使用字符串资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63454146/