可以說我有一個函式public static int Name(int num){}
但我希望能夠接收的不僅僅是一個 int 變數。不是 int 也不是字串,而是 int 或字串(例如)。我可以在不創建其他功能的情況下做到這一點嗎?
uj5u.com熱心網友回復:
我會用兩種同名的方法來處理它。這稱為多載方法:
public static int Name(string num){ return Name(int.Parse(num));}
public static int Name(int num){}
這顯然沒有錯誤處理。
我將添加一個更有用的示例,這允許用戶發送單個電子郵件地址或它們的串列......
public static async Task SendMail(string to, string subject, etc)
{
await SendMail(new List<string> {to}, subject, etc);
}
public static async Task SendMail(List<string> toList, string subject, etc)
{
//The process of sending a mail
}
uj5u.com熱心網友回復:
使用型別聯合:
是的。使用型別 union ,該型別表示一組特定型別中一個特定型別的值。
C# 和 .NET 沒有內置支持(即一流的聯合型別),但出色的 OneOf 庫也可以正常作業:
所以你的方法是這樣的:
public static Int32 Name( OneOf< Int32, String > num ) // rename `num` to something else if it isn't always going to be a number.
{
if( num.TryPickT0( out Int32 i32Value, out String strValue ) )
{
// do stuff with i32Value
}
else
{
// do stuff with strValue
}
}
因為已經定義了和(但沒有其他型別)OneOf<T0,T1>的隱式轉換,這意味著您可以像這樣呼叫您的方法:T0T1Name
Int32 name0 = Name( 123 ); // `(Int32)123` is implicitly converted to OneOf<Int32,String> by the compiler for you.
Int32 name1 = Name( "abc" ); // `(String)"abc"` is implicitly converted to OneOf<Int32,String> by the compiler for you.
// But you'll get a compile-time error if you use an unsupported type, e.g.:
Int32 name2 = Name( 456.2f ); // `(Single)456.f` cannot be implicitly converted to OneOf<Int32,String>, so you get a compile-time error.
替代方案:濫用Object作為窮人的頂級型別:
.NET 沒有任何型別的真正頂級型別(即可以正確表示任何型別的值的型別,包括void,以及表示沒有裝箱的值型別);我們最接近的是Object型別,它是(幾乎)所有參考型別的超型別,也代表裝箱的值型別。
因此,如果您希望引數型別集不受限制并且不介意裝箱,也不介意失去編譯時安全性(因此不介意運行時例外......),那么您可以做到可怕Object地用作粗略的頂級型別:
public static Int32 Name( Object num ) // rename `num` to something else if it isn't always going to be a number.
{
if( num is Int32 i32Value )
{
// do stuff with i32Value
}
else if( num is String strValue )
{
// do stuff with strValue
}
else
{
throw new ArgumentException( message: "Unsupported argument type.", paramName: nameof(num) );
}
}
Single...但是現在它是不安全的,因為如果你傳入一個( float) 值,編譯器不會給你一個錯誤,這與 with 不同OneOf<>:
Int32 name0 = Name( 123 ); // Int32 boxed and widened to Object.
Int32 name1 = Name( "abc" ); // String widened to Object.
Int32 name2 = Name( 456.2f ); // Single widened to Object. No compile-time error. Instead this will fail at runtime.
uj5u.com熱心網友回復:
使用動態關鍵字
public static dynamic foo(int bar) {
if (bar == 1) {
return 1;
} else if (bar == 2) {
return "two";
}
return 0;
}
uj5u.com熱心網友回復:
您可以指定多個輸出,而不是將函式指定為 int:
static (bool approved, string outname) Name(int num)
{
if (num == 0)
{
return (true, "Poul");
}
else if (num == 1)
{
return (true, "Hans");
}
else
{
return (false, "Noname");
}
}
然后你可以從函式中呼叫值:
var getName = Name(1);
Console.WriteLine(getName.approved);
Console.WriteLine(getName.outname);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457179.html
標籤:C#
