Here is my code
public interface ITranslator<E, R>
{
E ToEntity<T>(R record);
}
class Gens : ITranslator<string, int>
{
#region ITranslator<string,int> Members
public string ToEntity<MyOtherClass>(int record)
{
return record.ToString();
}
#endregion
}
When I compile this, I get an error Type parameter declaration must be an identifier not a type
Why is that I cannot have ToEntity<MyOtherClass>
but can only have ToEntity<T>
??
Edit: what is MyOtherClass
doing ? I am converting between entities(POCOs equivalent of Entity framework) and record(Object returned by the framework) for multiple tables/classes. So I would want to use this to do my class specific conversion
Your interface has a generic ToEntity<T>
method that you've made non-generic in your implementation class Gens
as ToEntity<MyOtherClass>
. (A generic method could take any type parameter, possibly given certain constraints on T
. Your Gens
class is trying to provide a definition for ToEntity
only for the type parameter MyOtherClass
, which defeats the purpose of generics.)
In your code example, it's unclear how your Gens
class is trying to use the MyOtherClass
type; it's certainly not involved in the logic of ToEntity
. We'd need more information to be able to guide you further.
To illustrate, here's what your current definition of the ITranslator<E, R>
interface offers, in plain English:
"I provide a mechanism to translate any record of type
R
into an entity of typeE
, this mechanism being dependent upon any user-specified typeT
."
Your Gens
class, on the other hand, the way it's currently designed, "implements" the above interface like so:
"I can translate integers to strings. I provide the illusion of allowing the user to specify a type to control how this translation is performed, but in fact there is no choice of type. The
MyOtherClass
class is involved somehow; that's all I can say."
From these two descriptions, it's clear that the Gens
class is not really doing what the ITranslator<E, R>
interface guarantees . Namely, it is not willing to accept a user-specified type for its ToEntity
method. That's why this code won't compile for you.
您必须在泛型类型上声明约束。
public string ToEntity<T>(int record) where T : MyOtherClass
That compiles OK for me in LINQpad.
Maybe you have a type named E, R, or T somewhere?
Ahh I see what you're trying to do... you have MyOtherClass defined as a class somewhere yet you're trying to use it as a type argument in ToEntity. How exactly do you want MyOtherClass involved in ToEntity?
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.