【问题标题】:How do I pass a string to a function requiring an Object?如何将字符串传递给需要对象的函数?
【发布时间】:2013-11-30 05:08:13
【问题描述】:

我正在使用 Chello(Trello API 的 c# 包装器)。我需要根据此处的文档传递参数“createCard”:https://trello.com/docs/api/card/index.html

这是我在 Chhello 中使用的函数:

public IEnumerable<CardUpdateAction> ForCard(string cardId, object args)
    {
        string queryString = BuildQueryString(args);

        return GetRequest<List<CardUpdateAction>>("/cards/{0}/actions?{1}", cardId, queryString);
    }

我试过这样称呼:

 List<CardUpdateAction> cua = chello.CardUpdates.ForCard("5264d37736695b2821001d7a","createCard").ToList();

但我收到错误:参数计数不匹配

关于这个功能:

 protected static string BuildQueryString(object args)
    {
        string queryString = String.Empty;
        if (args != null)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var prop in args.GetType().GetProperties())
            {
                sb.AppendFormat("{0}={1}&", prop.Name, prop.GetValue(args, null));
            }
            if (sb.Length > 0) sb.Remove(sb.Length - 1, 1);
            queryString = sb.ToString();
        }
        return queryString;
    }

【问题讨论】:

    标签: c# function args trello


    【解决方案1】:

    string 是一个object。 .NET 平台中的每种类型都继承自Object。这称为Unified Type System

    另一方面,我们有Liskov Substitution Principle,简单地说,如果 B 是 A 的子类型(B 是 A),那么您应该能够在使用 A 的任何地方使用 B。

    基于这些原因,您可以将字符串传递给任何接受对象作为参数的方法。

    你可以测试一下:

    public void DoSomething(object args)
    {
    }
    
    public void Main()
    {
        DoSomething("some string argument, instead of the object");
    }
    

    它工作得很好。没有错误。

    【讨论】:

      【解决方案2】:

      问题在于,您使用的 API 要求您传入一个公共属性等于您要使用的标签的类。

      使用Anonymous Types 很容易做到这一点(我正在做一个稍微不同的例子来帮助说明一个观点)

      //This will cause BuildQueryString to return "actions=createCard&action_fields=data,type,date"
      var options = new { actions = "createCard", action_fields = "data,type,date" };
      
      List<CardUpdateAction> cua = chello.CardUpdates.ForCard("5264d37736695b2821001d7a",options).ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-25
        • 2012-01-01
        • 1970-01-01
        • 2018-12-24
        • 2013-01-21
        • 1970-01-01
        • 2019-11-16
        • 1970-01-01
        相关资源
        最近更新 更多