试用dynamic
2010-09-30 22:47:04 来源:WEB开发网早就听说过C#4.0中添了dynamic,但一直没去了解它,今天无意中看到,看起来的确很Cool。
有了dynamic,就可以把C#当javascript用了。
不知道,这个功能是福是祸!不知道,在啥情况下应该用它!
下面是使用DynamicDictionary与Dictionary的对照:
public class DynamicDictionary : DynamicObject
{
Dictionary<string, object> _dictionary = new Dictionary<string, object>();
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_dictionary[binder.Name] = value;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _dictionary.TryGetValue(binder.Name, out result);
}
}
[TestFixture]
public class TestDynamicDict
{
[Test]
public void Using_Dict()
{
var dict = new Dictionary<string, object>();
dict["Hello"] = "hELLO";
dict["World"] = "wORLD";
Console.WriteLine("{0},{1}", dict["Hello"], dict["World"]);
}
[Test]
public void Using_Dynamic_Dict()
{
dynamic dict = new DynamicDictionary();
dict.Hello = "hELLO";
dict.World = "wORLD";
Console.WriteLine("{0},{1}", dict.Hello, dict.World);
}
}
更多精彩
赞助商链接