I've declared an interface with Add method to add new item, 2 classes TopicModel and CommentModel to store data.
I've re-write the code in console mode, like this:
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);
}
}
}
The line topic.Add(t, c) gave me error message:
The type arguments for method 'Topic.Add(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Then, I've tried again with:
topic.Add(c, c) // Good :))
topic.Add(t, t, t); // That's okay =))
That's my problem. I want the method accepts 2 different types (TopicModel and CommentModel).
And, I don't want to declare:
interface IAction
{
void Add(TopicModel t, CommentModel c);
}
because another classes can re-use Add method within different argument types.
So, my question is: how to change params T[] t to accept multiple argument types?
Addmethod is expected to work with? For example, can it work for theinttype? In the body of theAddmethod, you are explicitly casting the first parameter toTopicModeland the second toCommentModel, this means that you are expecting these specific types. You need to add more context to the question about what theAddmethod is supposed to do.topic.Add(t, c)totopic.Add(t, t)ortopic.Add(c, c)object array, don't you?asand fret about what to do when it generates null.