首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >字符串作为new运算符的泛型参数

字符串作为new运算符的泛型参数
EN

Stack Overflow用户
提问于 2015-11-18 23:24:33
回答 2查看 76关注 0票数 0

我想将属性名作为参数传递:

代码语言:javascript
运行
复制
   protected T findControl<T>(string myProperty, string myPropertyValue , UITestControl control = null) where T : UITestControl, new()
    {
        var uiContainer = control ?? Window;
        return uiContainer.SearchFor<T>(new { myProperty = myPropertyValue });
    }

 public static T SearchFor<T>(
        this UITestControl control,
        dynamic searchProperties,
        dynamic filterProperties = null) where T : UITestControl, new() 

我使用:

代码语言:javascript
运行
复制
return findControl<HtmlComboBox>("id", "PersonComboBox")

调试时,我得到:

代码语言:javascript
运行
复制
dynamic searchProperties = {myProperty = PersonComboBox}

我想说的是:

代码语言:javascript
运行
复制
dynamic searchProperties = {id = PersonComboBox}

为什么会这样呢?有没有办法解决这个问题?

EN

回答 2

Stack Overflow用户

发布于 2015-11-19 00:28:56

同意Andrew Sun的观点- dynamics不是很流行的特性,它唯一的用法是处理COM互操作或特殊的API,如Newton.Json、MongoConnector (在这些地方它不是很流行--大多数开发人员更喜欢他们的字典重载)。

如果你想以.net -最好的方式给动态的东西留下印象,使用最接近JS对象行为的集合和容器。

此任务最常用的类是- Dictionary<string,object> (几乎与JS对象完全相同)或Dictionary<string,string> (如果它真的是字符串,只有映射,没有嵌套)。

如果您必须提供嵌套-您仍然可以使用Dictionary<string,object>,但对于某些场景,XElement可能是更好的选择。

我不建议在没有很大理由的情况下使用Newton.JSON,因为它是附加依赖的,是一种瑞士刀-你只会使用它提供的1%的服务。

当你想到动态是好的--记住--这只是一种低效的实现,它会导致项目的CSharp依赖和运行时编译的过热。我和我认为许多其他人不建议使用它们,而不是非常特殊的情况。

票数 1
EN

Stack Overflow用户

发布于 2015-12-02 01:12:38

我也同意我前面的演讲者所说的,在这里使用字典可能是一个更容易的解决方案,但是如果你仍然想在这里使用动态,你可以尝试以下方法:

代码语言:javascript
运行
复制
protected T findControl<T>(string myProperty, string myPropertyValue, UITestControl control = null) where T : UITestControl, new()
{
  var uiContainer = control ?? Window;
  // create an expando object here and reference it as dictionary
  IDictionary<string, object> searchProperties = new ExpandoObject();
  // now add your data to the dictionary
  searchProperties.Add(myProperty, myPropertyValue);
  // call your method with your newly created expando object,
  // in your method, you can now call "searchProperties.id"
  // and also your debug view (open the "Dynamic View" item in VS debugger)
  // should show a property called "id"
  return uiContainer.SearchFor<T>(searchProperties);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33783932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档