编写代表而不会弄乱代码 [英] Write Delegates without messing up the code

查看:67
本文介绍了编写代表而不会弄乱代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在写这样的代表。



 委托  void  MyMethod( string  arg1, string  arg2); 
MyMethod mm;





我不知道为什么它需要两行来声明一个委托。如果我的班级有20名代表,我需要编写40行代码。

有人能用一行代码告诉我一个写这个的方法吗?

先谢谢你。

解决方案

< blockquote>第一行是委托的定义(你可以将它与类,结构或枚举定义进行比较)。

第二行声明一个变量,它将你的委托作为类型。

这些都不是一回事。你不能在一个声明中混合它们。

干杯。


追逐最少的行数是愚蠢的。您应该尝试编写促进更好可读性的行数,不要重复相同的代码,等等。



然而,绝对没有办法写那些代表类似你写的那个。您可以使用泛型解决此类问题。您甚至不必定义泛型类型或方法:.NET BCL中的几个定义已经涵盖了包括您在内的99%的重要案例。这就是你能做的:

 System.Action< string,string> mm; 



这不是全部。如果要立即使用某个委托实例初始化 mm> ,则甚至不需要编写单独的(命名)方法。以下是您可以执行的操作,例如:

 System.Action< string,string> mm =  new  System.Action< string,string>((s1,s2)= >  {
System.Console.WriteLine( @ 第一个参数:{0};第二个参数: {1},s1,s2); // 或其他任何内容
});



要了解这一切是如何运作的,请阅读以下主题:1)泛型,2)匿名方法; 3)lambda表达式和方法; 4)作为奖励:关闭。



顺便说一句,我建议在开始写任何内容之前从头到尾阅读一些语言和.NET手册(超越学习练习)并试图改进某些东西。首先,你需要知道现有的东西。



-SA


Hi,

I am writing delegates as like this.

delegate void MyMethod(string arg1, string arg2);
MyMethod mm;



I don't know why it needs two lines to declare a single delegate. If my class has 20 delegates, I need to write 40 line of code.
Can anybody tell me a way to write this in one line of code ?
Thanks in Advance.

解决方案

The first line is the definition of the delegate (you can compare it to a class, struct or enum definition).
The second line declares a variable which has your delegate as type.
These are not the same things. You cannot mix them in a single statement.
Cheers.


Chasing minimal number of lines is just silly. You should try to write the number of lines promoting better readability, never repeating the same code, and so on.

However, there is absolutely no way to write those delegate types like the one you wrote. You can solve such problems using generics. You don't even have to define generic types or methods: several definitions in .NET BCL already cover some 99% of practically important cases including yours. This is what you can do:

System.Action<string, string> mm;


That's not all. You don't even need to write a separate (named) method if you want immediately initialize mm> with some delegate instance. Here is what you can do, for example:

System.Action<string, string> mm = new System.Action<string, string>((s1, s2) => {
    System.Console.WriteLine(@"First argument: ""{0}""; second argument:""{1}""", s1, s2); // or anything else
});


To understand how it all works, read on the following topics: 1) generics, 2) anonymous methods; 3) lambda expressions and methods; 4) as a bonus: closures.

By the way, I would advise to read some language and .NET manual from the beginning to the end before writing anything serious (beyond learning exercises) and trying to improve something. First, you need to know what is already available.

—SA


这篇关于编写代表而不会弄乱代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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