簡體   English   中英

使用字符串參數實例化類型以動態構造函數

[英]Instantiate type with string parameter to constructor dynamically

我有以下代碼:

if (FileType == typeof(ScanUploadFile))
{
    files.Add(new ScanUploadFile(filePath));
}
if (FileType == typeof(FaxFile))
{
    files.Add(new FaxFile(filePath));
}
if (FileType == typeof(BulkScanFile))
{
    files.Add(new BulkScanFile(filePath));
}
if (FileType == typeof(SpecialCategoryFile))
{
    files.Add(new SpecialCategoryFile(filePath));
}

沒有IF語句怎么寫?

由於您只對構造函數感興趣,因此可以使用:

 Activator.CreateInstance(FileType, new string[] {filePath});

Activator器在System庫中定義。

使用Type對象的GetConstructors方法,並選擇一個具有字符串類型的單個參數的對象,然后調用它。

像這樣:

private ConstructorInfo GetStringConstructor(Type type)
{
    return (from ctor in type.GetConstructors()
            let pars = ctor.GetParameters()
            where pars.Length == 1 && pars[0].ParameterType == typeof(string)
            select ctor).FirstOrDefault();
}

像這樣使用它:

var ctor = GetStringConstructor(typeof(Test));
if (ctor != null)
    files.Add(ctor.Invoke(new string[] {filePath}));

我為提取構造函數提供了一個單獨的方法,但是如果您僅打算使用它來實際創建實例,則可以在一個采用stringType參數的方法中對所有元素進行重構。 但是要注意正確的錯誤處理。

但是 ,我將在這里考慮Factory方法模式 ,而不僅僅是立即進行反思。 我不知道它是否更適合您的需求,但似乎確實可以。

編輯:有人在乎解釋降票嗎? 我承認CreateInstance更好,但是我的方法具有更多控制權和更好的錯誤處理優勢,因此我認為至少應在此處介紹

暫無
暫無

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

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