简体   繁体   中英

How to put generic Type (T) as parameter?

I have this error:

Severity    Code    Description Project File    Line
Error   CS0246  The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) 

on the method signature for this method:

 public static void SendMessage(string queuName, T objeto)
        {
            QueueClient Client =QueueClient.CreateFromConnectionString(connectionString, "Empresa");
            BrokeredMessage message = new BrokeredMessage(objeto);
            message.ContentType = objeto.GetType().Name;
            Client.Send(new BrokeredMessage(message));
        }
public static void SendMessage<T>(string queuName, T objeto)
{
    QueueClient Client =QueueClient.CreateFromConnectionString(connectionString, "Empresa");
    BrokeredMessage message = new BrokeredMessage(objeto);
    message.ContentType = objeto.GetType().Name;
    Client.Send(new BrokeredMessage(message));
}

You forgot to specify the type parameter. You can do that in 2 ways:

Either you define them at the method definition (which is the way to go in your case, because your method is static):

public static void SendMessage<T>(string queuName, T objeto)

Or you can specify them on the class definition (for instance methods):

class MyClass<T>{
    public void SendMessage(string queuName, T objeto){}
}

The correct syntax for your example is:

public static void SendMessage<T>(string queuName, T objeto)
{
// Type of T is
Type t = typeof(T);
// Obtain Name
string name = t.Name
// Create another instance of T
object to = Activator.CreateInstance<T>();
// etc.
}

In general:

T method<T>(T param) where T: restrictions //new() for example
{ return (T)Activator.CreateInstance<T>(); }

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