簡體   English   中英

使用params關鍵字和動態類型參數

[英]Using params keyword with dynamic type arguments

我已經使用Add方法聲明了一個接口來添加新項目,2個類TopicModelCommentModel來存儲數據。

我在控制台模式下重寫代碼,如下所示:

interface IAction
{
    void Add<T>(params T[] t) where T : class;
}

class TopicModel
{
    public string Id { get; set; }
    public string Author { get; set; }
}

class CommentModel
{
    public string Id { get; set; }
    public string Content { get; set; }
}

class Topic : IDisposable, IAction
{
    public void Add<T>(params T[] t) where T : class
    {
        var topic = t[0] as TopicModel;
        var comment = t[1] as CommentModel;

        // do stuff...
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

class MainClass
{
    static void Main()
    {
        var t = new TopicModel { Id = "T101", Author = "Harry" };
        var c = new CommentModel { Id = "C101", Content = "Comment 01" };

        using (var topic = new Topic())
        {
            //topic.Add(t, c);
        }
    }
}

topic.Add(t, c)給了我錯誤信息:

無法從用法推斷出方法'Topic.Add(params T [])'的類型參數。 嘗試顯式指定類型參數。

然后,我再次嘗試:

topic.Add(c, c) // Good :))
topic.Add(t, t, t); // That's okay =))

那是我的問題。 我希望該方法接受2種不同的類型( TopicModelCommentModel )。

並且,我不想聲明:

interface IAction
{
    void Add(TopicModel t, CommentModel c);
}

因為另一個類可以在不同的參數類型中重用Add方法。

所以,我的問題是:如何更改params T[] t以接受多個參數類型?

TopicModel和CommentModel必須繼承相同的類或實現相同的接口。 嘗試這個 :

interface IAction
{
    void Add<T>(params T[] t) where T : IModel;
}

class IModel
{
}

class TopicModel : IModel
{
    public string Id { get; set; }
    public string Author { get; set; }
}

class CommentModel : IModel
{
    public string Id { get; set; }
    public string Content { get; set; }
}

class Topic : IDisposable, IAction
{
    public void Add<T>(params T[] t) where T : IModel
    {
        var topic = t[0] as TopicModel;
        var comment = t[1] as CommentModel;

        Console.WriteLine("Topic witch ID={0} added",topic.Id);
        Console.WriteLine("Commment witch ID={0} added", comment.Id);
    }

    public void Dispose()
    {

    }
}

class Program
{
    static void Main()
    {
        TopicModel t = new TopicModel { Id = "T101", Author = "Harry" };
        CommentModel c = new CommentModel { Id = "C101", Content = "Comment 01" };

        using (var topic = new Topic())
        {
            topic.Add<IModel>(t, c);
        }

        Console.ReadLine();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM