c# - 不能在 NSSet<TKey> 中使用类

标签 c# ios xamarin

我正在尝试为 Xamarin 的 iOS 框架创建绑定(bind),但它在某些 NSSet 属性的泛型类型上遇到了困难:

// @interface Foo : NSObject
[BaseType(typeof(NSObject))]
interface Foo
{ ... }

// @interface Bar : NSObject
[BaseType(typeof(NSObject))]
interface Bar
{
    // @property (readonly, nonatomic) NSSet<Foo *> * _Nonnull foos;
    [Export("foos")]
    NSSet<Foo> foos { get; }
}

产生错误

Error CS0311: The type 'Namespace.Foo' cannot be used as type parameter 'TKey' in the generic type or method 'NSSet'. There is no implicit reference conversion from 'Namespace.Foo' to 'ObjCRuntime.INativeObject'.

我不明白错误是因为Foo类是基于NSObject的,为什么会产生这个错误?

最佳答案

Foundation.NSSet<TKey> Class 声明为

[Foundation.Register("NSSet", SkipRegistration=true)]
public sealed class NSSet<TKey> : NSSet, IEnumerable<TKey>
    where TKey : class, INativeObject

即,您的混凝土 TKey必须是实现 INativeObject 的类. Foo才不是。如果你改变 Foo

interface Foo : INativeObject
{ }

...编译器错误消失。


where TKey : class, INativeObject(generic) Type Parameter Constraint .它告诉您 TKey 的类型参数必须是通过 class 的引用类型关键字并且它必须实现接口(interface) INativeObject .

关于c# - 不能在 NSSet<TKey> 中使用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52666538/

相关文章:

c# - 使用 MVVM 模式正确设置项目

c# - 将 selectlistitems 绑定(bind)到 viewmodel 的正确方法

c# - 在c#中声明一个静态类型的成员

ios - 如何在 UITableView 中设置 UILabel 的高度以包含可变长度的 NSString

ios - '应用程序试图用 swift 3 模态呈现一个事件 Controller '

Xamarin 表单 : Hide a Stack While Scrolling a list

c# - 在 ASP.NET MVC4 中——我需要编辑一条记录并向其添加许多(1 到许多)子记录(在顶级记录的编辑模式下)

ios - 整个 session 的 Apple AR Kit 功能点

使用 Xamarin Studio 时 iOS 应用程序不会自动启动

c# - 如何在 Xamarin.Forms 中实现 INotifyPropertyChanged