C# 创建采用可选参数变量类型的方法

C# 创建采用可选参数变量类型的方法,c#,C#,在NET framework的Console类中,Console.WriteLine()将许多不同的对象类型作为参数。在VisualStudio中键入时,这一点很明显,intellisense会显示具有不同数据类型的箭头键。或者在采用多个参数的方法中,您可以看到intellisense描述根据已输入的对象类型进行更新 一个屏幕截图来说明我试图解释的内容: 如何编写一个可以接受多种类型的方法?它被称为重载,您只需创建一个名称相同但参数不同的方法: /// <summary> /// W

在NET framework的Console类中,
Console.WriteLine()
将许多不同的对象类型作为参数。在VisualStudio中键入时,这一点很明显,intellisense会显示具有不同数据类型的箭头键。或者在采用多个参数的方法中,您可以看到intellisense描述根据已输入的对象类型进行更新

一个屏幕截图来说明我试图解释的内容:


如何编写一个可以接受多种类型的方法?

它被称为重载,您只需创建一个名称相同但参数不同的方法:

/// <summary>
/// Writes a string followed by a newline to the console
/// </summary>
/// <param name="s">The value to write</param>
public void WriteLine(string s)
{
    //Do something with a string
}

/// <summary>
/// Writes the string representation of an object followed by a newline to the console
/// </summary>
/// <param name="o">The value to write</param>
public void WriteLine(object o)
{
    //Do something with an object
}
//
///将后跟换行符的字符串写入控制台
/// 
///要写入的值
公共无效写线(字符串s)
{
//用绳子做某事
}
/// 
///将后跟换行符的对象的字符串表示形式写入控制台
/// 
///要写入的值
公共无效写入线(对象o)
{
//用物体做某事
}
要获得良好的intellisense描述,可以向每个方法添加

您可以使用

您可以使用不同的输入类型定义多个方法,并使用适合您使用的方法

例如:

public int AddTwoNumbers(int a, int b)
{
    return a + b;
}

public int AddTwoNumbers(double a, double b)
{
    return (int) a + b;
}

这两个函数都返回一个整数,但它们采用不同的类型,处理不同类型的代码也不同。

这一特性在面向对象编程中称为方法重载 只需创建具有不同签名的方法(函数采用的参数类型和数量)

您可以在此处阅读有关方法重载的更多信息: “WriteLine”方法有很多不同的参数,它表示重载,例如:

public static void HowLong(int x)
{
    //TODO: implement here
}

public static void HowLong(String x)
{
    //TODO: implement here
} 

static void Main(string[] args)
{
    HowLong(1);
    HowLong("1");
}

添加xml注释以获得良好的intellisense描述我认为从
double+double
方法返回
int
并不是方法重载有用的最佳演示…不,但这是一个简单的例子,初学者甚至不知道什么是方法重载
public static void HowLong(int x)
{
    //TODO: implement here
}

public static void HowLong(String x)
{
    //TODO: implement here
} 

static void Main(string[] args)
{
    HowLong(1);
    HowLong("1");
}