zoukankan      html  css  js  c++  java
  • KeyValue Coding(KVC),KeyValue 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

    欢迎大家扫描下面二维码成为我的客户,为你服务和上云

  • 相关阅读:
    python3使用django1.11不支持MYSQL-python的解决办法
    abp学习目录
    日常网站整理
    C#使用TransactionScope实现事务代码
    CSS禁止选择
    数据库三种事务
    设计模式总章
    几种排序方法的总结
    将图片压缩成大小格式小的图片
    常用的wsdl地址
  • 原文地址:https://www.cnblogs.com/shanyou/p/1948936.html
Copyright © 2011-2022 走看看