Gilbert,
Unfortunately, no, there isn't. The default constructor constraint is
the only one.
You could use reflection in the static constructor to check the type
parameter to see if it has the constructor that you require, but this has
the side effect of not giving you a compile-time check, just a run-time
check.
If you don't need a specific constructor, rather, if you can have an
initializer method, then I would create an interface with that method, and
implement it on your classes (if you can). Either that, or create an
interface which will act as a class factory, with one method with the
parameters you need. Then, you can have implementations of that class which
will create the classes. Something like this:
interface IPersonFactory< T>
{
public T Create(string name, int age);
}
class Person
{
public string Name;
public int Age;
}
class PersonFactory : IPersonFactory< Person>
{
public Person Create(string name, int age)
{
Person retVal = new Person();
retVal.Name = name;
retVal.Age = age;
return retVal;
}
}
class PersonUtils<TFa ctory, TPersonwhere TFactory : IPersonFactory
{
}
This way, you can have a class which will construct the instances you
need, which implements a factory interface which you can use in whatever
class you were going to make generic in the first place.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard. caspershouse.co m
"gilbert@gm ail" <gi************ @gmail.comwrote in message
news:11******** **************@ k79g2000hse.goo glegroups.com.. .
Hello.
I am trying to use c# generic to define a class.
class MyClass<Twhere T: new(){
}
In this definition, MyClass can create T objects with a default
constructor. Is there any way to set the constraint such that MyClass
can create T objects with some custom constructors (provided that T
has such a cstr)?
Thank you very much!
Gilbert