请问,如何将这段C#代码转换为C++实现?
//-- DependencyProperty --//
public class DependencyProperty
{
internal static Dictionary<object, DependencyProperty> RegisteredDps = new Dictionary<object, DependencyProperty>();
internal string Name;
internal object Value;
internal object HashCode;
private DependencyProperty(string name, Type propertyName, Type ownerType, object defaultValue)
{
this.Name = name;
this.Value = defaultValue;
this.HashCode = name.GetHashCode() ^ ownerType.GetHashCode();
}
public static DependencyProperty Register(string name, Type propertyType, Type ownerType, object defaultValue)
{
DependencyProperty dp = new DependencyProperty(name, propertyType, ownerType, defaultValue);
RegisteredDps.Add(dp.HashCode, dp);
return dp;
}
}
//-- DependencyObject --//
public class DependencyObject
{
private string _unUsedField;
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(DependencyObject), string.Empty);
public object GetValue(DependencyProperty dp)
{
return DependencyProperty.RegisteredDps[dp.HashCode].Value;
}
public void SetValue(DependencyProperty dp, object value)
{
DependencyProperty.RegisteredDps[dp.HashCode].Value = value;
}
public string Name
{
get
{
return (string)GetValue(NameProperty);
}
set
{
SetValue(NameProperty, value);
}
}
}
主要是语法功能
public void SetValue(DependencyProperty dp, object value),最后面的object是C#所有对象的基类,包括int、string、float等,这点对我来说比较麻烦。最好能不用模块,用any也行,其它方式更好,实现不行模板也OK。
谢谢!!
[解决办法]
自己定义一个object,要有虚析构,然后派生出int_obj、double_obj……
用map<string, boost::shared_ptr<object> >代替dictionary
这个问题不适合用模板,因为模板会导致生成不同的类,使用不同的map……无法将不同类型统一处理。用boost::any当然也可以,不过我不习惯使用那种东西,用object系列虽然需要多写不少代码,但更清晰,并且保证类型安全,需要时我们还可以给它们加上一些虚函数——这是any很难做到的。
如果想省事,又不想用boost,那就用map<string, string>,所有数据转化为字符串,需要时再从字符串读取数据。
[解决办法]
不就是C#的一个依赖属性的实现嘛