我有几个数据类,想要从列表中选择一个项目。我们想使用lambda表达式来实现。但是当select属性在基类中时,似乎没有按预期工作。 基类
public class BaseData
{
public bool isSelected;
public int distance;
}
派生类
public class PlayerData: BaseData
{
public string nickname
}
一些逻辑
public class SelectData
{
public PlayerData GetPlayer()
{
List<PlayerData> playerdata = new List<PlayerData>();
// this list gets its data from a JSON file and is populated as expected.
// now we want to select the player data for processing.
PlayerData player = playerdata.Find(x => x.isSelected);
// on this part we unexpected results, when i move the isSelected to the class PlayerData it works perfect but than it is not possible to write a generic extensions with these Data classes.
return player;
}
}
我们想要使用类似
的扩展名public static int AddToDropDown<T>(this Dropdown dropdown,
List<T> baseDataList,
string displayText,
string iconName,
bool isSelected) where T : new() {
enter code here --- add to dropdown and add the item to PlayerData or ...
}
没有编译器错误......出了什么问题?
答案 0 :(得分:0)
对我来说它运作正常: 在这里看到这个例子,可能还有其他原因导致了这个问题:
public void Main()
{
List<PlayerData> playerdata = new List<PlayerData>
{
new PlayerData
{
isSelected = true,
distance = 3,
nickname = "First",
},
new PlayerData
{
isSelected = true,
distance = 3,
nickname = "Second",
},
new PlayerData
{
isSelected = true,
distance = 3,
nickname = "Third",
}
};
PlayerData player = playerdata.Find(x => x.isSelected);
Console.WriteLine(player);
}
public class BaseData
{
public bool isSelected;
public int distance;
}
public class PlayerData: BaseData
{
public string nickname;
public override string ToString() { return this.nickname;}
}
结果是'First',因为它是列表中的第一个玩家。