标签:c# 属性绑定
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();
}
}
}结果:
本文出自 “Better_Power_Wisdom” 博客,请务必保留此出处http://aonaufly.blog.51cto.com/3554853/1947974
标签:c# 属性绑定
原文地址:http://aonaufly.blog.51cto.com/3554853/1947974