温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C# 属性绑定

发布时间:2020-09-20 12:16:18 来源:网络 阅读:785 作者:Aonaufly 栏目:编程语言

C#的反射明显的比AS3的反射要强很多啊。可以从外部访问到类的私有成员。举个例子:

                Type _class = this.GetType();
                FieldInfo _field = _class.GetField(@fieldName, BindingFlags.Instance | BindingFlags.NonPublic);

枚举 : BindingFlags.NonPublic ->非公共成员将包括在内进行搜索,意思就是private成员也可以搜索到。


在model中注册须发的主题(User)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BindLib.com;

namespace BindDemo.com.model
{
    public sealed class User : BaseDataModel
    {
        private int _hp = 1000;
        public int Hp
        {
            get { return _hp; }
            //绑定hp(血量)
            set { this.ChangeValue<int>("Hp","_hp",value); }
        }

        private bool _isLive = false;

        public bool IsLive
        {
            get { return _isLive; }
            set { this.ChangeValue<bool>("IsLive", "_isLive", value); }
        }
    }
}

这的注意的是字段_hp和字段_isLive都是private(私用的): 这个和AS3绑定(见 AS3 属性绑定/上一篇)有很大的不同,这得益于C#可以从外部访问private


view中需要绑定(注册侦听)(UserView)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BindLib;

namespace BindDemo.com.model
{
    public sealed class UserView
    {
        public User user;
        private int _hp;
        public int Hp
        {
            set { 
                this._hp = value ;
                Console.WriteLine("血量 {0}", value);
            }
            get { return this._hp; }
        }
        public UserView()
        {
            user = new User();
            BindTools.BindProperty<int>(this, "Hp", user, "Hp", true);
            BindTools.BindSetter<bool>(this.UpdateIsLive, user, "IsLive",true);
        }

        private void UpdateIsLive(bool @isLive)
        {
            Console.WriteLine(@isLive ? "活着" : "战死");
        }

    }
}

好了 , 具体参数意思可以参考(《AS3 属性绑定》篇,上篇)

测试:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BindDemo.com.model;

namespace BindDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            UserView _uM = new UserView();
            Console.WriteLine("获得hp : {0}" , _uM.Hp);
            User uR = _uM.user;
            uR.Hp = 89;
            Console.WriteLine("改变获得hp : {0}", _uM.Hp);
            Console.WriteLine("-------------------------------------------------");
            uR.IsLive = true;
            Console.WriteLine("#################################################");
            uR.IsLive = false;
            Console.ReadLine();
        }
    }
}

结果:

C# 属性绑定


附件:http://down.51cto.com/data/2366862
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI