簡體   English   中英

如何在變量中存儲將用於代替通用類的類的名稱?

[英]How to store in a variable the name of the class that will be used in place of a generic class?

為了重構代碼,我創建了一個基類,其中放置了所有常用功能。 我被這個要轉換為方法的委托所困擾。

 Func<LogImportTestArgs, IList<TranslationTask>> 
 getParserWithMocks = (args) =>
 {
         return TestParserWithMocks<MyGenericClass>(
                parserConstName: args.ParserConstName,
                logFileName: args.LogFileName,
                srcLocale: args.SrcLocale,
                tgtLocale: args.TgtLocale,
                tlType: args.TranslationType,
                ttype: args.TTtype,
                logMappingID: args.LogMappingID
      );
   };

除了我不知道如何存儲在變量中的泛型類之外,其他所有內容都很簡單。 我試圖將類的名稱存儲為字符串,但是用字符串替換MyGenericClass時出現錯誤。

protected IList<TranslationTask> getParserWithMocks(LogImportTestArgs args)
{
         return TestParserWithMocks<MyGenericClass>(
                parserConstName: args.ParserConstName,
                logFileName: args.LogFileName,
                srcLocale: args.SrcLocale,
                tgtLocale: args.TgtLocale,
                tlType: args.TranslationType,
                ttype: args.TTtype,
                logMappingID: args.LogMappingID
      );
   };

有沒有辦法在變量中存儲泛型類的值? 否則,我將不得不在每個測試中復制/粘貼相同的方法。 我想在中央可以修改此方法。

謝謝。

如果要在MyGenericClass參數化MyGenericClass ,則需要使函數通用:

protected IList<TranslationTask> GetParserWithMocks<T> (LogImportTestArgs args)
{
    return TestParserWithMocks<T>(
        parserConstName: args.ParserConstName,
        logFileName: args.LogFileName,
        srcLocale: args.SrcLocale,
        tgtLocale: args.TgtLocale,
        tlType: args.TranslationType,
        ttype: args.TTtype,
        logMappingID: args.LogMappingID
    );
};

然后,當您調用函數時,您將需要傳入通用類型:

IList<TranslationTask> tasks = GetParserWithMocks<MyGenericClass>(args);

不確定我是否完全理解,但似乎您希望該方法是通用的:

protected IList<TranslationTask> getParserWithMocks<T>(LogImportTestArgs args)
{
     return TestParserWithMocks<T>(
            parserConstName: args.ParserConstName,
            logFileName: args.LogFileName,
            srcLocale: args.SrcLocale,
            tgtLocale: args.TgtLocale,
            tlType: args.TranslationType,
            ttype: args.TTtype,
            logMappingID: args.LogMappingID
      );
   };

暫無
暫無

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

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