Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
声明c#函数_C# - Fatal编程技术网

声明c#函数

声明c#函数,c#,C#,我创建了一个名为MyClass的类,有点像这样: public class MyClass { public int MyInt {get;set;} public int MyInt2 {get;set;} } 现在我想创建一个函数,该函数接受int作为参数,并返回MyClass对象列表 我对语法一窍不通。是否为公共静态列表MyFunction(int MyParam)?我没有理智 谢谢。您很可能想要: public static List<MyClass> MyFuncti

我创建了一个名为MyClass的类,有点像这样:

public class MyClass
{ public int MyInt {get;set;}
  public int MyInt2 {get;set;}
}
现在我想创建一个函数,该函数接受int作为参数,并返回MyClass对象列表

我对语法一窍不通。是否为公共静态列表MyFunction(int MyParam)?我没有理智

谢谢。

您很可能想要:

public static List<MyClass> MyFunction(int myParam)
{
    // ....
公共静态列表MyFunction(int myParam)
{
// ....
是泛型列表,这是MyClass列表的最佳选项(因为它是类型安全的)。它需要使用System.Collections.generic;将其添加到文件顶部(或完全限定它)。

公共静态列表MyFunction(int-myParam){
接受int参数并返回MyClass实例列表似乎是ok语法


如果您没有获得intellisense支持(假设您使用的是VS.NET),则源代码中可能存在一些语法错误


说到intellisense,如果您在VS.NET中对源文件中的任何类型按下
Ctrl+。
,VS.NET将自动搜索该类型,并为您在源文件中添加using语句。

如果列表部分没有intellisense,请确保您有一个“using System.Collections.Generic;”在文件/名称空间的顶部。返回类型为
IList
可能会带来更大的灵活性。即使开发人员不需要它,对接口的理解也不会有什么坏处。@David:True-
IEnumerable
可能会更好。(不过,我必须承认,
List
经常被用作“特殊的”框架中的case并直接返回-像ToList()这样的方法可以返回
IList
,但不…)我通常也会选择
IEnumerable
我自己(或者更确切地说,使用最高的通用抽象),但这将取决于开发人员在这里需要做什么。我们对代码的理解不够,他可能需要在公共位置使用实际的列表功能(添加、删除等)。当然,总是有
.ToList()
,但是如果方法总是返回列表,那么就没有理由进一步抽象。