Reputation: 469
When Method
require any string
we write that
void method(string str)
{
str="OK";
}
I have a method
that require any class
.
Little part of my method
:
Void Post()
{
responsefromserver = new JavaScriptSerializer.Deserialize<T>(sr.ReadToEnd());
}
T
-must be any class
.
But I don't know how should I declare that my method
require any class
?
Upvotes: 2
Views: 65
Reputation: 13541
Make it generic:
void Post<T>()
{
responsefromserver = new JavaScriptSerializer.Deserialize<T>(sr.ReadToEnd());
}
And then use it like:
Post<YourClass>();
You can constraint your generic method if needed.
Upvotes: 2
Reputation: 236268
Make your method generic and add generic parameter constraint:
void Post<T>()
where T: class
{
responsefromserver = new JavaScriptSerializer.Deserialize<T>(sr.ReadToEnd());
// ...
}
You can parametrize it with any class:
Post<FooClass>(); // OK if FooClass is a class
Post<int>(); // fail, because integer is a value type
Upvotes: 3
Reputation: 62544
You just inject dependency as a parameter or in your case - better to inject deserializer, and probably not on the Post()
method level but on a class constructor level then reuse in Post()
.
Upvotes: 0