简体   繁体   中英

Generics method inside of generics method

I have function like this

public static void serialize<T>(T serializeObject){
    //this is the trouble
    SerializableEntity<T> entity = new SerializableEntity<T>(serializeObject);
}

How can I make that in using generics inside of generics? How to accomplish this?

UPDATE

Here the compiler error:

错误图片

There is nothing wrong per-se with the code you have: that compiles fine:

class SerializableEntity<T> {
    public SerializableEntity(T obj) { }
}
static class P {
    public static void serialize<T>(T serializeObject) {
        //this is fine...
        SerializableEntity<T> entity =
            new SerializableEntity<T>(serializeObject);
    }
    static void Main() { /*...*/ }
}

So the real question is: what does the compiler say ? The most obvious one would be if it says something like:

The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method ' SerializableEntity<T> '

which is a "constraint" violation; if that is what you are seeing you need to add the constraints to serialize<T> to prove to the compiler that the constraints are always satisfied. For example, if SerializableEntity<T> is declared as:

class SerializableEntity<T> where T : class
{...}

then you simply transfer that constraint to the method:

public static void serialize<T>(T serializeObject) where T : class
{...}

Note that other constraints are possible, including:

  • : class
  • : struct
  • : SomeBaseType
  • : ISomeInterface
  • : new()

You probably have different constraints on T in the method and in the class.

Take in mind that if the class says:

where T  : class, IDisposable 

Then the method has to have at least the same where

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM