0

I wrote this method that takes in a generic parameter object. This method accepts different parameter objects with different properties. The idea is that based on the value of the "MethodName" property, I can construct a URI base on properties of that particular parameter object

I use reflection to get the value of the property named "MethodName." It's not a method, just a property name.

I use the value of the MethodName property in a case statement. This seems like an inferior way to accomplish my task. Especially as the number of MethodNames grow.

Below is the source with the case statement implementation. Any help would be appreciated.


    public string ConstructBBAPIUri<T>(T parameters)
    {
        var methodName = "";
        var uri = "";
        var userId = "";
        long timeStamp = 0;
        var signature = "";
        var sessionKey = "";
        var newUserId = "";

        if (parameters != null)
        {
            methodName = parameters.GetType().GetProperty("MethodName").GetValue(parameters, null).ToString();

            switch (methodName)
            {
                case "user.login":
                    userId = parameters.GetType().GetProperty("UserId").GetValue(parameters, null).ToString();
                    timeStamp = Convert.ToInt64(parameters.GetType().GetProperty("TimeStamp").GetValue(parameters, null));
                    signature = GenerateBunchBallSignature(userId);

                    uri = "method=" + methodName + "&apiKey=" + apiKey + "&userid=" + userId + "&ts=" +
                          timeStamp + "&sig=" + signature;
                    break;

                case "user.modifyUserId":

                    //We shouldn't need the session key if user.login is being called first
                    userId = parameters.GetType().GetProperty("UserId").GetValue(parameters, null).ToString();
                    newUserId = parameters.GetType().GetProperty("NewUserId").GetValue(parameters, null).ToString();

                    uri = "method=" + methodName + "&sessionKey=" + sessionKey + "&oldUserId=" + userId +
                          "&newUserId=" + newUserId;
                    break;
            }
        }

        return uri;
    }
4

2 回答 2

4

更好的设计是委托类上的 URI 构造。

  1. 使用 ConstructBBAPIUri() 方法创建接口;
  2. 为您具有代码访问权限的新类或现有类实现接口
  3. 对于您无权访问代码的现有类,从这些类继承并实现接口。希望这些类所需的所有属性都可以访问,否则使用反射。
于 2012-11-15T02:43:28.223 回答
0

一种选择是将函数添加到字典中,但我看不出这会比当前方法好得多,而且它会更加混乱和容易出错。

我认为 Max Shmelev 暗示的将是最好的解决方案。如果可以的话,为每个将被传递的类添加一个接口,并为这个方法添加一个通用约束。该接口将定义一个方法,当在对象中实现时,该方法将处理该对象的序列化。

如果列表不太长,您可以为要处理的每种不同类型添加方法,并且在每种情况下只调用一个方法。

于 2012-11-15T02:33:36.257 回答