帮助转换“样板”代码到C#泛型 [英] Help converting "boilerplate" code to C# generics

查看:62
本文介绍了帮助转换“样板”代码到C#泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前在C#编程中没有使用泛型,但我认为我找到了它们的用途。我只是不知道如何将这个样板代码转换为单个通用...



在下面的示例代码中,PlayBall方法和变量通过它(以及变量的类型)是每次运行这组代码时的变化。有时候,方法调用也没有参数。



有没有办法将它转换为通用?



谢谢!



I haven't used generics before in my C# programming, but I think I have found a use for them. I just don't know how to go about converting this boilerplate code to a single generic...

In the example code below, the PlayBall method and the variable passed to it (along with the variable's type) are what changes from each time this set of code is run. Sometimes also, the method call takes no arguments either.

Is there a way to convert this to a generic?

Thanks!

lock (slaveLocker)
{
    foreach (KeyValuePair<Tuple<string, string>, ICallbacks> kvp in slaves)
    {
        try
        {
           kvp.Value.PlayBall(ball);
        }
        catch
        {
           slaves.Remove(kvp.Key);
        }
    }
}

推荐答案

问题本身不正确。您不可能将此代码片段转换为泛型。您可以将通用参数添加到类型声明中(它将生成不完整的泛型类型,应通过具体通用参数实例化获取完整类型)或方法声明。



您已使用泛型类型 KeyValuePair 元组,现在需要使用创建自己的类型或方法仿制药。在紧要关头,查看上面提到的两种泛型类型的声明,以查看语法。然后阅读MSDN文档中的泛型声明。这非常非常简单:

http://msdn.microsoft.com /en-us/library/512aeb7t.aspx [ ^ ]。



因为你没有提供将任何东西变成泛型的基础(没有类型或方法声明),此时弥补代码示例没什么帮助。如果您阅读文档,将会更容易。



-SA
The question itself is incorrect. You cannot possibly convert this fragment of code to generic. You can add a generic parameters to a type declaration (it will make an incomplete generic type, a complete type should be obtained by instantiation with concrete generic parameters) or to a method declaration.

You already used generic types KeyValuePair and Tuple, now you need to create your own type or method using generics. In a pinch, look at the declarations of the two generic types mentioned above, to see the syntax. And then read on generic declarations in MSDN documentation. This is really, really simple:
http://msdn.microsoft.com/en-us/library/512aeb7t.aspx[^].

As you did not provide a base for turning anything into generics (no type or method declaration), at this moment making up a code sample would be of little help. If you read documentation, it will be a lot easier.

—SA


这篇关于帮助转换“样板”代码到C#泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆