2016-03-06 34 views
2

我已经宣布了一个接口与Add方法添加新项目,2类TopicModelCommentModel来存储数据。使用params关键字与动态类型参数

我重新写在控制台模式下的代码,就像这样:

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接受多个参数类型?

+7

该代码根本不是通用的。您希望调用者传递正确类型的参数,但编译器无法实际验证和执行该参数。你可能会使用* object *。 –

+0

“Add”方法有望与哪些类型配合使用?例如,它可以为'int'类型工作吗?在Add方法的主体中,您明确地将第一个参数转换为'TopicModel',将第二个参数转换为'CommentModel',这意味着您期待这些特定类型。您需要为有关“Add”方法应该做什么的问题添加更多上下文。 –

+0

@YacoubMassad如果我把'topic.Add(t,c)'改为'topic.Add(t,t)'或'topic.Add(c,c)',那么它不会给我任何错误' –

回答

3

TopicModel et 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(); 
    } 
} 
+0

非常感谢!这是帮助:) –

+0

不客气。 :) – Coding4Fun