[英]Using params keyword with dynamic type arguments
我已經使用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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.