[英]How to put generic Type (T) as parameter?
我有这个错误:
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));
}
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));
}
您忘记指定type参数。 您可以通过2种方式做到这一点:
您可以在方法定义中定义它们(由于您的方法是静态的,因此是您的情况):
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>(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.