我正在拼命尝试调整一个API,我希望从这个API中获取一个特定的数值,而我似乎无法做到这一点。
具体来说,我试图从名称为Controller的API中获取自定义字段名称和值,值是用户给它的值(字符串值)。
为了达到这个目的,我需要使用所谓的IGame接口,它具有多个属性和方法。所有属性都与游戏一起使用,并使用属性的名称。例如,game.title
或game.Platform
。
因此,执行this.Controller.Text = game.Title;
会将游戏标题输出到UI。到目前为止,非常好。
使用这些方法时出现问题,将自定义字段包含在内。我必须使用GetAllCustomFields
,其语法为ICustomField[] GetAllCustomFields()
。返回值为ICustomField[]
,其语法依次为public interface ICustomField
,其属性为GameId
,Name
,Value
。
不幸的是,API没有提供有关实际使用情况的进一步信息,因此我离开时试图弄清楚但无济于事。
这是我到目前为止所拥有的:
public void OnSelectionChanged(FilterType filterType, string filterValue, IPlatform platform, IPlatformCategory category, IPlaylist playlist, IGame game)
{
if (game == null)
{
this.Controller.Text = "HellO!";
}
else
{
foreach (string field in game.GetAllCustomFields(ICustomField[Name]))
{
this.Controller.Text = "The " + Name + " is " + Value;
}
}
}
XAML
<Grid>
<TextBox x:Name="Controller" />
</Grid>
有人可以帮助我重组foreach
以便实际上有效吗?
答案 0 :(得分:1)
var controllerFields = game.GetAllCustomFields().Where(f => f.Name == "Controller");
foreach (var field in controllerFields)
{
this.Controller.Text = "The " + field.Name + " is " + field.Value;
}
或者它只是一个Controller-field:
Controller.Text = game.GetAllCustomFields()
.SingleOrDefault(f => f.Name == "Controller")
?.Value ?? "No controller here";
如果找到该字段, ?.Value
将返回该字段的值。如果没有,该问号将阻止访问.Value
,因为它会导致NullReferenceException。通过添加?? "No controller here"
,您将获得一个回退,如果未找到Controller字段,则返回该回退。该opererator(?.
)被称为null coalescing operator,如果您还不知道的话。