如何将泛型类型(T)作为参数

本文关键字:参数 泛型类型 | 更新日期: 2023-09-27 18:01:36

我有这个错误:

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?) 
这个方法的方法签名上的

:

 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));
        }

如何将泛型类型(T)作为参数

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));
}

您忘记指定类型参数了。有两种方法:

或者在方法定义时定义它们(这是您的情况,因为您的方法是静态的):

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

或者您可以在类定义中指定它们(例如实例方法):

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

您的示例的正确语法是:

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.
}
一般

:

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