我有type根據我需要創建不同的物件。一件特定的事情——所有的物件都有一些共同的部分。
所以我想為他們準備一些基類。并且在每個單獨的類中只添加特定的屬性。
class BaseClass {
public int Prop1 {get;set;}
public string Prop2 {get;set;}
}
class MyClass1 : BaseClass {
public int PropMyClass1 {get;set;}
}
class MyClass2 : BaseClass {
public string PropMyClass2 {get;set;}
}
我想過創建工廠:
interface ICreator<T>{
bool CanHanlde(string type);
T Create();
}
class Creator1: ICreator<MyClass1>
{
bool CanHandle(string type) {return "type1" == type;}
MyClass1 Create();
}
class Creator2: ICreator<MyClass2>
{
bool CanHandle(string type) {return "type2" == type;}
MyClass2 Create();
}
現在我想創建一些工廠,它將根據型別回傳 concreate 類。問題 - 我不知道如何將型別傳遞給泛型。我需要從哪里獲取型別?我可以注冊所有型別ICreator并用 DI 注入它。選擇true在CanHandle方法中回傳的那個。但不知道如何獲取泛型型別。
uj5u.com熱心網友回復:
我可以為 ICreator 注冊所有型別并用 DI 注入它。選擇在 CanHandle 方法中回傳 true 的那個。但不知道如何獲取泛型型別。
真是奇怪的問題。我的理解是你想迭代可用的型別,CanHandle如果方法回傳 true,則呼叫并回傳該型別。這將需要實體化每種型別的實體。可能這不是您想要的,有很多方法會出錯,甚至無法進行編譯時檢查。但這里是如何做到這一點。
首先,使用反射來獲取可用的型別。然后將型別過濾為實作介面的型別。然后實體化類。在類上呼叫“CanHandle”(介面說它會存在),如果為真,你就找到了你的類。
您可以按程式集/命名空間分隔您的類,以便更輕松地查找特定類。
using SomeNamespace;
using System.Reflection;
namespace SomeNamespace
{
public class MyClass1 { public int Id { get; set; } }
public class MyClass2 { public int Id { get; set; } }
public interface ICreator<T>
{
bool CanHandle(string type);
T Create();
}
public class Creator1 : ICreator<MyClass1>
{
public Creator1() { }
public bool CanHandle(string type) { return "type1" == type; }
public MyClass1 Create() { return new MyClass1(); }
}
public class Creator2 : ICreator<MyClass2>
{
public Creator2() { }
public bool CanHandle(string type) { return "type2" == type; }
public MyClass2 Create() { return new MyClass2(); }
}
}
namespace SomeOtherNamespace
{
internal class Program
{
static void Main(string[] args)
{
var types = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.IsClass && t.Namespace == "SomeNamespace")
.ToList();
var typeNameToTest = "type2";
foreach (var type in types)
{
if (type.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICreator<>)))
{
// Requires resolving to a matching constructor, the default constructor (no arguments) is implemented above.
var newInstance = Activator.CreateInstance(type);
// pick any implementation for nameof...
// Probably this can fail if `CanHandle` doesn't exist.
var canHandleMethod = type.GetMethod(nameof(Creator1.CanHandle));
// This can fail if the signature for `CanHandle` ever changes.
bool canHandleResult = (bool)canHandleMethod.Invoke(newInstance, new object[] { typeNameToTest });
if (canHandleResult)
{
Console.WriteLine($"Found class that can handle type \"{typeNameToTest}\": {newInstance.GetType().FullName}");
break; // or return newInstance
}
}
}
}
}
}
控制臺輸出:
Found class that can handle type "type2": SomeNamespace.Creator2
另請參閱如何確定型別是否實作特定的泛型介面型別以及如何獲取命名空間中的所有類?.
uj5u.com熱心網友回復:
這將是一個簡單的解決方案,我希望它對您有所幫助:類Creator應該只實體化一次,并使用它可以處理的型別串列。
public interface ICreator<T>{
bool CanHanlde(string type);
T Create(string type);
}
public class Creator: ICreator<BaseClass>
{
List<string> handleTypes;
public Creator(List<string> supportedTypes)
{
this.handleTypes= supportedTypes;
}
public bool CanHandle(string type)
{
return this.handleTypes?.Contains(type);
}
public BaseClass Create(string type)
{
switch(type)
{
case "type1": return new MyClass1();
case "type2": return new MyClass2();
}
return null;
}
uj5u.com熱心網友回復:
由于您正在從資料庫中以字串形式查詢型別,因此您有一個動態場景。即,您只在運行時知道型別。
泛型型別總是在編譯時決議。因此,它們在這里沒有幫助。MyClass1具體來說,從工廠回傳具體型別 ( , )并沒有多大幫助MyClass2,因為您無法在運行時鍵入變數。您必須BaseClass在編譯時使用。
// You don't know whether this will return MyClass1 or MyClass2 at runtime
BaseType result = creator.Create(typeStringFromDb);
您可以在 switch 陳述句中使用型別模式來訪問專用屬性:
BaseType result = creator.Create(typeStringFromDb);
switch (result) {
case MyClass1 obj1:
int prop1 = obj1.PropMyClass1;
...
break;
case MyClass2 obj2:
string prop2 = obj2.PropMyClass2;
...
break;
default:
break;
}
您仍然可以使用泛型介面使其可用于其他基本型別,但您必須使用基本型別對其進行初始化。
interface ICreator<TBase>{
string Handles { get; }
TBase Create();
}
我建議不要讓方法CanHandle回傳布林值,而是在字串屬性中回傳已處理的型別。這允許您將工廠存盤在字典中并將此字串用作鍵。
我將在一個靜態類中使用靜態建構式來設定字典。
// Given the classes
class Creator1 : ICreator<BaseClass>
{
public string Handles => "type1";
public BaseClass Create() => new MyClass1();
}
class Creator2 : ICreator<BaseClass>
{
public string Handles => "type2";
public BaseClass Create() => new MyClass2();
}
// The static creator
static class Creator
{
private static readonly Dictionary<string, ICreator<BaseClass>> _creators = new();
static Creator()
{
ICreator<BaseClass> creator1 = new Creator1();
ICreator<BaseClass> creator2 = new Creator2();
_creators.Add(creator1.Handles, creator1);
_creators.Add(creator2.Handles, creator2);
}
public static BaseClass Create(string type)
{
if (_creators.TryGetValue(type, out var creator)) {
return creator.Create();
}
return null; // Or throw exception.
}
};
用法
BaseClass result = Creator.Create("type1");
更新1,回傳具體型別
不同的變體回傳專門的型別,但需要一個 switch 陳述句(或 switch 運算式)來處理不同的型別。如果要訪問派生類的其他成員 ( PropMyClass1, PropMyClass2),則無法避免這種情況。
我們像這樣宣告介面。注意out關鍵字。它使泛型型別協變。這允許我們將不同的創建者添加ICreator<object>到字典中。
interface ICreator<out T>
{
T Create();
}
Creator 工廠現在使用型別為的字典鍵System.Type:
static class Creator
{
private static readonly Dictionary<Type, ICreator<object>> _creators = new();
static Creator()
{
_creators.Add(typeof(MyClass1), new Creator1());
_creators.Add(typeof(MyClass2), new Creator2());
}
public static T Create<T>()
{
if (_creators.TryGetValue(typeof(T), out var creator)) {
return ((ICreator<T>)creator).Create();
}
throw new ArgumentException("Non supported type", nameof(T));
}
};
具體創建者現在回傳特殊型別:
class Creator1 : ICreator<MyClass1>
{
public MyClass1 Create() => new MyClass1();
}
class Creator2 : ICreator<MyClass2>
{
public MyClass2 Create() => new MyClass2();
}
用法:
switch (typeStringFromDb) {
case "type1":
MyClass1 obj1 = Creator.Create<MyClass1>();
int prop1 = obj1.PropMyClass1;
//TODO: Do MyClass1 stuff
break;
case "type2":
MyClass2 obj2 = Creator.Create<MyClass2>();
string prop2 = obj2.PropMyClass2;
//TODO: Do MyClass2 stuff
break;
default:
break;
}
更新 2,使用多型
但也許你應該以不同的方式處理事情并使用多型性。為此,我們必須以一種允許我們使用附加屬性而無需知道確切的型別別的方式來制定類。這樣,我們將始終與BaseClass.
現在,我們將基類實作為具有抽象方法來處理附加屬性的抽象類
abstract class BaseClass
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
abstract public void DoStuffWithAdditionalProperty();
}
class MyClass1 : BaseClass
{
public int PropMyClass1 { get; set; }
public override void DoStuffWithAdditionalProperty()
{
//TODO: use PropMyClass1 here
}
}
class MyClass2 : BaseClass
{
public string PropMyClass2 { get; set; }
public override void DoStuffWithAdditionalProperty()
{
//TODO: use PropMyClass2 here
}
}
創建者界面不再是通用的:
interface ICreator
{
string Handles { get; }
BaseClass Create();
}
實作創建者和創建者工廠現在很簡單,我不會在這里展示。
用法:
BaseClass result = Creator.Create("type1");
result.DoStuffWithAdditionalProperty();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511210.html
下一篇:使用泛型的Swift列舉值
