Key-Value Coding(KVC),Key-Value Observing(KVO)和Cocoa Bindings for MonoMac
Key-Value Coding(KVC)机制允许通过变量名设置(set)以及获取(get)变量值。变量名只是一个字符串,但通常我们称之为Key。KVC也就是Cocoa访问NSObjects的属性的方式而不用直接访问对象的属性。
比如说你有个对象叫做Movie,有三个属性:Title,Producer,Year。
using System;
using System.Collections.Generic;
namespace KVC
{
public partial class Movie
{
public Movie () {}
public string Title { get; set; }
public string Producer { get; set; }
public int Year { get; set; }
}
}
可以直接通过对象Movie的属性访问到:
Movie movie = new Movie();
movie.Title = "Shrek - Forever After"; // to assign the value
var title = movie.Title; // to read the property value
使用KVC可以直接通过NSObject的方法访问到属性的字符串值:
- 设置属性的值SetValueForKey (NSObject value, NSString key)
- 读取属性的值ValueForKey(NSString key)
Movie movie = new Movie();
movie.SetValueForKey((NSString)"Shrek - Forever After",(NSString)"Title");; // to assign the value
var title = movie.ValueForKey((NSString)"Title"); // to read the property
这非常类似于.NET的反射机制
Movie movie = new Movie();
Type sourceType =movie.GetType();
PropertyInfo info = sourceType.GetProperty("Title");
info.SetValue(movie, "Shrek - Forever After" , null); // to assign the value
var title = info.GetValue(this,null)); // to read the property value
.NET类需要满足Key-Value Coding 编码规范,通过使用[Export("xxxxx")]进行装饰,xxxx就是Cocoa的Key了:
using System;
using System.Collections.Generic;
using MonoMac.Foundation;
namespace KVC
{
public partial class Movie : NSObject
{
public Movie () {}
[Export("title")]
public string Title { get; set; }
[Export("producer")]
public string Producer { get; set; }
[Export("year")]
public int Year { get; set; }
}
}
上面引入了MonoMac.Foundation命名空间,Movie类从NSObject类继承过来,三个属性使用Export属性修饰,这样Movie就可以满足Cocoa的KVC机制。
具体参考文章
http://cocoa-mono.org/archives/153/kvc-kvo-and-cocoa-bindings-oh-my-part-1/
欢迎大家扫描下面二维码成为我的客户,扶你上云

【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
2010-02-03 各种浏览器的userAgent