我已经宣布了一个接口与Add
方法添加新项目,2类TopicModel
和CommentModel
来存储数据。使用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种不同的类型(TopicModel
和CommentModel
)。
而且,我不想声明:
interface IAction
{
void Add(TopicModel t, CommentModel c);
}
,因为其他类可以重新使用不同的参数类型中Add
方法。
所以,我的问题是:如何更改params T[] t
接受多个参数类型?
该代码根本不是通用的。您希望调用者传递正确类型的参数,但编译器无法实际验证和执行该参数。你可能会使用* object *。 –
“Add”方法有望与哪些类型配合使用?例如,它可以为'int'类型工作吗?在Add方法的主体中,您明确地将第一个参数转换为'TopicModel',将第二个参数转换为'CommentModel',这意味着您期待这些特定类型。您需要为有关“Add”方法应该做什么的问题添加更多上下文。 –
@YacoubMassad如果我把'topic.Add(t,c)'改为'topic.Add(t,t)'或'topic.Add(c,c)',那么它不会给我任何错误' –