我用Add
方法声明了一个接口,以添加新项,2个类TopicModel
并CommentModel
存储数据。
我已经在控制台模式下重新编写了代码,如下所示:
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
为接受多个参数类型?
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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句