簡體   English   中英

返回T,其中返回類型不同

[英]Return T where are different return types

我有不同的返回類型,所以我無法決定該使用什么。 我在下面想類似的事情,但是如果您有其他想法,我會公開表示。

public T GetValue<T>(ContentType type)
{
    foreach (SyndicationItem item in feed.Items)
    {
        switch (type)
        {
            case ContentType.BaseUri:
                return item.BaseUri;
                break;
            case ContentType.Categories:
                return item.Categories;
                break;
            case ContentType.Content:
                return item.Content;
                break;
            case ContentType.Contributors:
                return item.Contributors;
                break;
            case ContentType.Copyright:
                return item.Copyright;
                break;
          }
     }
}

public enum ContentType
{
    BaseUri,
    Categories,
    Content,
    Contributors,
    Copyright
}

我想確定我要返回的類型,以便它匹配,否則將丟棄編譯時錯誤。

我沒有把開關盒放在for循環中的意義。 第一次出現這種情況時,您將退出循環。
但是要處理有關返回類型不確定性的問題,如果您知道返回類型將是引用類型,那么您也可以這樣做:

您可以將返回類型設置為object ,然后調用者必須進行強制轉換:

public object GetValue(ContentType type)
{
    switch (type)
    {
        case ContentType.BaseUri:
            return item.BaseUri;
            break;
        case ContentType.Categories:
            return item.Categories;
            break;
        case ContentType.Content:
            return item.Content;
            break;
        case ContentType.Contributors:
            return item.Contributors;
            break;
        case ContentType.Copyright:
            return item.Copyright;
            break;
      }
}

呼叫者:

public void Caller() 
{
    object x = GetValue();
    if ( x.GetType() == typeof(BaseUri) ) // I assume that BaseUri is also a class name
    {
        BaseUri baseUri = (BaseUri)x;
        // now you can use baseUri to initialize another variable in outer scopes ... or use it as a parameter to some method or ...
    }
    else if(x.GetType() == typeof(Category))
    {
        // the same logic of casting and using goes here too ...
    }
}

昨天我看到了這個,我很好奇如何復制它。

        // Summary:
        //     Returns value of specified property as Sandbox.ModAPI.Interfaces.ITerminalProperty.TypeName
        //
        // Parameters:
        //   block:
        //     block reference
        //
        //   propertyId:
        //     property id (name)
        //
        // Type parameters:
        //   T:
        //     required value type of Sandbox.ModAPI.Interfaces.ITerminalProperty.TypeName
        //
        // Returns:
        //     property value as Sandbox.ModAPI.Interfaces.ITerminalProperty.TypeName
        public static T GetValue<T>(this Ingame.IMyTerminalBlock block, string propertyId);

這就是你的稱呼。 item.GetValue<StringBuilder>("gpsCoords")
您可以詢問另一個具有不同類型的屬性。 item.GetValue<bool>("IsPerm")

代碼所有者: https : //github.com/malware-dev/MDK-SE

暫無
暫無

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

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