编辑: 似乎已证实尚不支持协变泛型。为了确保它在下一个版本中出现,请向 Xamarin 发送电子邮件并请求此功能。
以下代码给了我一个错误(在 linq 语句处)。相同的代码在 Microsoft clr c# 4.0 中运行良好。
错误:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<LinqTest.Person>' to 'System.Collections.Generic.IEnumerable<LinqTest.Entity>'. An explicit conversion exists (are you missing a cast?)
代码:
[Activity(Label = "LinqTest", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : Activity {
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
var names = new List<string> {
"Joe",
"Bob",
"Jim",
"Jane"
};
IEnumerable<Entity> query =
from e in names
select new Person() {Name = e};
SetContentView(Resource.Layout.Main);
var button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate {
button.Text = string.Format("{0}", query.Count());
};
}
}
public class Entity {
public string Name { get; set; }
}
public class Person : Entity {
public string Workplace { get; set; }
}
public class Animal : Entity {
public string FurColour { get; set; }
}
我是正确的还是我遗漏了什么?如果是的话,建议重构这个?
此外,如果是这样,请将此视为 monodroid 的官方功能请求 - 支持协变通用支持。 :)
谢谢。
最佳答案
目前 MonoTouch 和 Android 版 Mono 都不支持协方差。它将在未来的版本中得到支持(可能是在今年下半年的某个时间)。
关于generics - Monodroid 泛型不是协变的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8807564/