I have a function that returns an interface.
I want to avoid a bunch of IF ELSE and get the type via reflection. So I pass in the namespace, typename and assemblyname as strings and construct the type OK. However, I'm stuck at how to return it as an interface.
My interface is names ILevel2. The types I am returning all implement it so I hope the folllowing would work but no joy yet...
Could someone point me in the right direction.....
string instanceReq = String.Format("{0}.{1}, {2}", nameSpace, typName, assseblyName);
var myType = Type.GetType(instanceReq);
ILevel2 myInterface = myType.GetInterface("ILevel2");
return myInterface;
I get a compiler error on the line setting myInterface =.....
Error 114 Cannot implicitly convert type 'System.Type' to 'Level2Obligations.ILevel2'. An explicit conversion exists (are you missing a cast?) D:\TFS\StockMaster_ECodes\StockMaster_ECode_Admin_MVC5\WebAPI\ECode_Web_Api\Models\ECodeLevel2Request.cs 103 35 ECode_Web_Api
Adding more detail......
In a mess at the moment but as you can see - i'm trying to be more generic rather than IF (namesapaceandType == "bghjbj")
private ILevel2 GetDLLInstance(string namespaceAndType)
{
var assseblyName = "Level2_Mock_Api";
var nameSpace = "Level2_Mock_Api";
var typName = "MockAPI";
string instanceReq = String.Format("{0}.{1}, {2}", nameSpace, typName, assseblyName);
var myType = Type.GetType(instanceReq);
var myInterface = (ILevel2)myType.GetInterface("ILevel2");
return myInterface;
if (namespaceAndType.ToUpper() == "LEVEL2_MOCK_API.MOCKAPI")
{
return new Level2_Mock_Api.MockAPI();
}
else......
Aucun commentaire:
Enregistrer un commentaire