【问题标题】:When using WCF, Function Overloading rule?使用 WCF 时,函数重载规则?
【发布时间】:2023-03-27 20:05:01
【问题描述】:

我在我的项目中使用 Windows 通信服务 (WCF)。

在我的项目中,

我写的函数如下:

GetUserNameByUserId(int userId);
GetProductInformationByProductId(int productId);

但是这个命名已经一天比一天复杂了。

例如,我有 5 个参数要传递给函数,在这种情况下,函数名称将类似于:

GetStackOverFlowByStackByOverByFlowByIdByStackOverFlow(string stack, string over, string flow, int id, string stackOverFlow);

并假设我想获得 2 个参数,例如打击:

GetStackOverFlowByIdByStackOverFlow(int id, string stackOverFlow);

我想使用如下函数重载:

public void abc(int i)
{
    System.Console.WriteLine("abc" + i);
}
public void abc(string i)
{
    System.Console.WriteLine("abc" + i);
}
public void abc(string i,int j)
{
    System.Console.WriteLine("abc" + i + j);
}

也就是说,我想写下面的函数:

GetStackOverFlow(int id);
GetStackOverFlow(int id, string name);
GetStackOverFlow(int id, string name, string StackOver);
.
.

不是吗? 有什么方法吗? 还是我做得对?

我研究并发现: Function Overloading in WCF

public interface IMyService
{
   [OperationContract(Name = "GetStringWithParam")]
   string GetString(DateTime date);

   [OperationContract(Name = "GetStringWithoutParam")]
   string GetString();
}

他说

但我不喜欢它,因为它有时会导致混乱。

还有其他方法吗? 谢谢。

【问题讨论】:

  • 你为什么要写函数GetStackOverFlow(id, name) 来过滤id和名字?我假设“id”已经只返回一个对象。你还能过滤多少?
  • 好方法,但不要认为只有 id 有时一个 Id 可以有多行,所以我必须使用更多过滤器..

标签: c# wcf c#-4.0


【解决方案1】:

您可以使用类作为参数。

[DataContract]
public class MySearchSettings
{

    [DataMember]
    public int? ID { get; set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string StackOver { get; set; }

}

然后创建一个这样的方法:

public GetStackOverflowResponse GetStackOverflow(MySearchSettings searchSettings)
{
    var response = new GetStackOverflowResponse();
    try
    {
        User user = null;
        if (searchSettings == null)
            throw new ArgumentNullException("searchSettings");
        if (searchSettings.ID.HasValue)
            user = //queryByID;
        else if (!String.IsNullOrEmpty(searchSettings.Name))
            user = //queryByName;
        else if (!String.IsNullOrEmpty(searchSettings.StackOver))
            user = //queryByStackOver;
        response.User = user;
    }
    catch(Exception e)
    {
        response.ErrorMessage = String.Format("{0}: {1}",
                                              e.GetType().Name,
                                              e.Message);
    }
    return response;
}

我没有包含GetStackOverflowResponse class,但你明白了。 这样做的好处之一是,您可以在部署较新版本的服务时轻松扩展类,而不会破坏客户端的功能。

【讨论】:

  • 是的,有一些查询对象可能是我会去的方式。
【解决方案2】:

你做得很好,这就是你在 WCF 中重载方法的方式(使用 name 属性)。我没有看到比使用 name 属性重载方法更好的方法。

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多