C# 如何将泛型类型(T)作为参数?
我有一个错误:C# 如何将泛型类型(T)作为参数?,c#,azure,servicebus,C#,Azure,Servicebus,我有一个错误: 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
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));
}
publicstaticvoidsendmessage(字符串queuName,T objeto)
{
QueueClient=QueueClient.CreateFromConnectionString(connectionString,“Empresa”);
BrokeredMessage=新的BrokeredMessage(objeto);
message.ContentType=objeto.GetType().Name;
发送(新代理消息(消息));
}
您忘记指定类型参数。
您可以通过两种方式实现这一点:
要么在方法定义中定义它们(在您的案例中,这是一种方式,因为您的方法是静态的):
公共静态无效发送消息(字符串queuName,T objeto)
也可以在类定义中指定它们(例如实例方法):
class-MyClass{
public void SendMessage(字符串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.
}
publicstaticvoidsendmessage(字符串queuName,T objeto)
{
//T型是
类型t=类型(t);
//得名
string name=t.name
//创建T的另一个实例
对象to=Activator.CreateInstance();
//等等。
}
一般而言:
T method<T>(T param) where T: restrictions //new() for example
{ return (T)Activator.CreateInstance<T>(); }
T方法(T参数),其中T:restrictions//new()为例
{return(T)Activator.CreateInstance();}
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>(); }