I have a base class like so:
public class Base{
private string name = string.Empty();
public Base(string name){
this.name = name;
}
public string Name{get;set;}
}
and I have a generic class that inherits from the Base
class and also contains a method that returns an object of the generic type T
like so :
public SubClass<T>:Base{
public SubClass(string name):base(name){}
public T method(string parameter){
//do some stuff here and return T
return T;
}
}
and I instantiate an object of the SubClass
:
object instance = new SubClass<object>("name");
and I don't use the generic type in the constructor. the parameters in the SubClass
constructor are predefined types (eg string, int etc.). This implementation works fine BUT i'm wondering if this is this correct? is there another more appropriate way to do this. Thanx
Edit
The context: The Base
class is a class that handles the connection with CouchDB. so i provide the necessary info(username, pass, host, port and database name) and the SubClass
is a simple client for CouchDB. So when I create an object of the SubClass
I want to provide the credentials for the CouchDB and I want, also, to provide the model (eg Account model, Product model) that I expect from the database.
I am a bit puzzled looking at your code. Why do you store your instance of SubClass
in an object? That way you won't be able to invoke any members of your class (others than those inherited from System.Object
).
I want, also, to provide the model (eg Account model, Product model) that I expect from the database
I'll assume these different types of models implement a common interface, so the structure looks something like this:
public interface IModel
{
Foo GetFoo();
}
public class AccountModel : IModel
{
public Foo GetFoo()
{
// whatever
}
}
public class ProductModel : IModel
{
public Foo GetFoo()
{
// whatever
}
}
Since we know that the type parameter of SubClass
is an IModel
, it would be a good idea to place a type constraint on T
:
public class SubClass<T> : Base where T : IModel
{
public SubClass(string name) : base(name){}
public T Method(string parameter)
{
//do some stuff here and return T
return T;
}
}
And I'd use it like this:
SubClass<ProductModel> pm = new SubClass<ProductModel>("blurg");
IModel model = pm.Method();
Foo foo = model.GetFoo();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.