泛型,但用于另一个方法的参数

问题描述 投票:0回答:1

我正在为Unity制作一个简单易用的多人游戏系统,我想做的事情之一就是跨网络方法调用系统。例如,如果我希望其他玩家获取聊天消息,我可以调用一个在收件人计算机上采用一些参数的方法,并使用该信息创建消息。

到目前为止,我已经制作了一个非常简单的方法,它接受收件人的 ID、字符串形式的函数名称以及所需数量的对象参数。例如:

invokeMethod(2, "createChatMessage", "howdy")
这对我来说非常棒,但是对于那些不明白接收端的函数需要具有与
invokeMethod 相同的参数的确切数量和类型的人来说,没有任何保障
方法。

我想解决这个问题的方法是做一些类似于泛型的事情:

method1<int>(5);
但对于方法参数,它会强制您使用与给定函数相同的参数。如果
method2
的参数是 (int, String),那么它的用法如下:
method1<method2>(5, "hola");
这个想法是,如果参数不匹配,它会在编译时(甚至希望在编辑器中)出现错误。它本质上是模仿给定方法的参数,但以另一种方式使用它们。

除此之外,还需要一些额外的参数,例如收件人的 ID。

如果存在,请告诉我,否则我可以让它在运行时显示错误。

c# unity-game-engine generics methods
1个回答
0
投票

我可能猜错了,因为你的问题相当令人困惑,但据我所知,你可能正在寻找代表。这是两个例子:

private delegate void PrivateDelegate(string id, string value1, int value2);

public static void Main(string[] args)
{
    Test<PrivateDelegate>(Method1, Method2); // compile time error: Expected a method with 'void Method2(string, string, int)' signature
}

private static void Method1(string id, string value1, int value2)
{
}

private static void Method2(string id, string value1, string value2, int value3)
{
}

public static void Test<T>(T method1, T method2) where T : Delegate
{
}
public static void Main(string[] args)
{
    Test(Method1, Method2); // compile time error: The type arguments for method 'void Testing.Program.Test<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
}

private static void Method1(string id, string value1, int value2)
{
}

private static void Method2(string id, string value1, string value2, int value3)
{
}

public static void Test<T>(T method1, T method2) where T : Delegate
{
}

第一个示例之所以有效,是因为通过指定确切的委托,您可以轻松地看到哪个方法出了问题,并且有清晰的错误消息。但是,如果您无法像这样定义代表(无论出于何种原因),则第二个将起作用,但更不清楚哪个是错误的。但是,这些要求您在编译时同时拥有这两种方法。如果没有,那么您需要考虑以下问题:

public static void Main(string[] args)
{
    Console.WriteLine(Equal(Method1, Method2)); // false
    Console.WriteLine(Equal(Method1, Method3)); // true
}

private static void Method1(string id, string value1, int value2)
{
}

private static void Method2(string id, string value1, string value2, int value3)
{
}
    
private static void Method3(string id, string value1, int value2)
{
}
    
public static bool Equal(Delegate method1, Delegate method2)
{
    return method1.GetType() == method2.GetType();
}

此运行时检查通过比较类型(对于 void 返回为

Action
,对于非 void 返回为
Func
)来进行,(对于方法 1 和 2 之间的检查)将在
Action<string, string, int>
Action<string, string, string, int>
(好吧,不完全是这样,如果你将类型写入控制台,则有更多内容,但为了简单起见,这就是它检查的内容),并且因为它们不相等,所以返回 false。

这可能是你想要的,也可能不是,但是你的问题很难读懂,所以我试图从中得到什么。

© www.soinside.com 2019 - 2024. All rights reserved.