WEB开发网
开发学院软件开发C语言 试用dynamic 阅读

试用dynamic

 2010-09-30 22:47:04 来源:WEB开发网   
核心提示:早就听说过C#4.0中添了dynamic,但一直没去了解它,试用dynamic,今天无意中看到,看起来的确很Cool,有了dynamic,就可以把C#当javascript用了

早就听说过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);
    }
  }

Tags:试用 dynamic

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接