簡體   English   中英

用C#創建方法

[英]Creating Method in C#

我大約有9個,只是“ sourceVal”和“ Source”的值不同。 我想做一個方法,並為每個參數傳遞這兩個值,這樣我的代碼就更干凈了。 有沒有簡單的方法可以使這種方法成為現實?

foreach (KeyValuePair<int?, string> sourceVal in Source) {
            try {
                if (p.LeadOriginDetail != null) {
                    if (sourceVal.Value.ToUpper() == p.LeadOriginDetail.ToUpper()) {
                        sourceid = sourceVal.Key;
                        break;
                    } else {
                        sourceid = null;
                    }
                } else {
                    sourceid = null;
                }
            } catch (Exception ex) {
                CPCUtilities.LogGeneral("Error: " + ex.ToString());
            }
        }

謝謝!

是的,重寫它以使用FirstOrDefault ,然后您可以輕松地將其寫入方法(返回類型int?和參數IEnumerable<KeyValuePair<int?, string>> )。

選擇您的代碼。 Right click > Refactor > Extract Method

如果要手動重構,請嘗試以下操作:

int? Find(IEnumerable<KeyValuePair<int?, string>> items, string origin) {
    int? resId = null;
    foreach (KeyValuePair<int?, string> sourceVal in items) {
        try {
            if (origin != null) {
                if (sourceVal.Value.ToUpper() == origin.ToUpper()) {
                    resId = sourceVal.Key;
                    break;
                } else {
                    resId = null;
                }
            } else {
                resId = null;
            }
        } catch (Exception ex) {
            CPCUtilities.LogGeneral("Error: " + ex.ToString());
        }
    }
    return resId;
}

現在,您可以按以下方式調用此邏輯:

var sourceId = Find(Source, p.LeadOriginDetail);
var marketId = Find(Market, p.LeadOriginDetail);
var businessUnitId = Find(BusinessUnit, p.LeadOriginDetail);

有一種使用LINQ獲取第一個匹配ID的簡便方法-幾乎總是比滾動自己的循環更好的選擇,更不用說進行9個類似的循環了。

使用new ClassName[] { }語法創建一個數組:

foreach([itemclass] Source in new [collectionclass][] { Source1, Source2, Source3, Source4... }) {
    foreach (KeyValuePair<int?, string> sourceVal in Source) { 
        // everything else
    } 
}

例如,創建一個名為YourSampleMethod(); //的方法,並將其重命名為您想要的方法名稱

    private static void YourSampleMethod()
    {
        foreach (KeyValuePair<int?, string> sourceVal in Source) 
        { 
            try 
            { 
                if (p.LeadOriginDetail != null)
                { 
                    if (sourceVal.Value.ToUpper() == p.LeadOriginDetail.ToUpper())
                    { 
                        sourceid = sourceVal.Key; break; 
                    }
                    else 
                    { 
                        sourceid = null; 
                    } 
                } 
                else 
                { 
                    sourceid = null; 
                } 
            }
            catch (Exception ex) 
            { 
                CPCUtilities.LogGeneral("Error: " + ex.ToString()); 
            } 
         }
    }

我不明白您的意思是“ sourceVal的不同值”,因為sourceVal是循環的局部變量。

但是,如果問題在於您具有可以替換“源”類型的不同類型,則可以將代碼段提取到可以接受類型為參數的方法中

  IEnumerable<KeyValuePair<int?, string>>

我將創建如下所示的方法:

int? FindKeyForValue(IEnumerable<KeyValuePair<int?,string> sequence,string valueToFind)
{
    if(valueToFind!=null)
        return sequence
            .Where(string.Equals(pair.Value,valueToFind,StringComparison.CurrentCultureIgnoreCase))
            .Select(pair=>pair.Value)
            .FirstOrDefault();
    else
        return null;
}

或者,如果您願意:

int? FindKeyForValue(IEnumerable<KeyValuePair<int?,string> sequence,string valueToFind)
{
    if(valueToFind!=null)
        return sequence
            .FirstOrDefault(string.Equals(pair.Value,valueToFind,StringComparison.CurrentCultureIgnoreCase))
            .Key;
    else
        return null;
}

它比較短,但IMO較難閱讀。

您應該選擇故意使用的文化。 在大多數情況下,您將要使用不變的文化,而不是當前的文化。 我在代碼中使用了當前的區域性,因為這與您的原始代碼最接近。

暫無
暫無

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

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