.Net接口,用于已知的返回类型,但未知类型/数量的参数

Jas*_*ong 7 .net c# design-patterns interface azure

有没有办法在接口中指定已知的返回类型,但未知的数量/类型的参数.

我问的原因是我使用的是Windows Azure表存储,每个表都有不同的分区和行键以及不同的输入值.

我正在创建一个ITableOperations接口,代码将是这样的:

interface ITableOperations<T>
    where T : Azure.AzureTableEntity
{
    // Key specification
    string PartitionKey(/* ? What should go here  */);

    // Key specification
    string RowKey(/* ? What should go here  */);
}
Run Code Online (Sandbox Code Playgroud)

项目表...对于另一个表,输入参数将是不同的

public class ScheduledItem : ITableOperations<ScheduledPostEntity>
{
    public string PartitionKey(Guid userGuid)
    {
        return userGuid.ToString();
    }
    public string RowKey(DateTime dateScheduled)
    {
        return dateScheduled.ReverseTicks();
    }
}
Run Code Online (Sandbox Code Playgroud)

Mig*_*elo 2

C#通过使用关键字支持数组形式的多个参数params

你可以这样做:

interface ITableOperations<T>
    where T : Azure.AzureTableEntity
{
    // Key specification
    string PartitionKey(params object[] data);

    // Key specification
    string RowKey(params object[] data);
}
Run Code Online (Sandbox Code Playgroud)

如果您已经知道参数的替代方案,那么您可以使用重载。假设您有一个可以接收字符串或 Guid 或两者的方法,您可以这样做:

    string PartitionKey(Guid guid);
    string PartitionKey(string str);
    string PartitionKey(Guid guid, string str);
Run Code Online (Sandbox Code Playgroud)

如果您使用 C# 4,则可以使用可选参数:

    string PartitionKey(Guid guid = default(Guid), string str = null);
Run Code Online (Sandbox Code Playgroud)