Fork me on GitHub

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的反射代码显得有点长河丑陋,使用MonoMac的Cocoa将非常的优雅。
.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/

http://tirania.org/monomac/archive/2010/Dec-07.html

posted @   张善友  阅读(1589)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题: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
点击右上角即可分享
微信分享提示