簡體   English   中英

C#-取決於預期類型的​​方法行為

[英]C# - method behaviour that depends on the expected type

是否可以用C#方法編寫

 String contestId = getParameter("contestId")

我在字符串中獲取了raceId,但是當我寫時:

 int contestId = getParameter("contestId")

我將raceId解析為整數?

這只是顯示我嘗試實現的簡單示例。

不,不可能僅根據其返回類型來重載方法。 但是,您可以引入一個通用參數:

T getParameter<T>(string input) {
    // ... do stuff based on T ...
}

如果使用的是C#3.0,則可以使用以下方法:

var str = getParameter<string>("contestid");
var integer = getParameter<int>("contestid");

因此只說一次實際類型。

可以做的一件事是返回一個單獨的對象,該對象具有對int和string的隱式轉換運算符。 那將非常接近您所要求的行為。

我不會在實踐中這樣做。 隱式轉換通常會帶來比其價值更大的麻煩。

而是添加一個通用參數,如Mehrdad所示:

var str = getParameter<string>("contestid");
var integer = getParameter<int>("contestid");

我更喜歡這種方法,它讀起來很好。

Public Class ResultProxy
{
  Private Object _Obj
  Public ResultProxy(Object O)
  { _Obj = O; }

  Public T As<T>()
  { return (T)_Obj; }
}

...

Public ResultProxy getParameter("contestId")
{
// your method's code
   return new ResultProxy(YourPersonalFavorateReturnType);
}

...

String s = getParameter("contestId").As<String>();

首先,答案是沒有很多人提到的。 為什么? 您是否必須將方法的結果分配給某些對象? 例如你可以

int getValue()
{
  return 4;
}

getValue();

答案是肯定的,所以可以,因此編譯器無法通過返回類型知道要調用的方法。

個人意見在這里,但我會建議一些類似的建議

public string getContestIdAsString(string ConetestId);

public int getContestIdAsInt(string ContestId);

每個人都在做什么很明顯,您就可以解決問題。 除非我缺少某些東西。

public T GetParameter<T>(string parameterName)
{
   //Do work
   return value
}

string contestId = getParameter<string>("contestId")
int contestId = getParameter<int>("contestId")

這是您最好的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM