简体   繁体   中英

How to create reference of an interface class through Reflection in C#

I'm using repository structure in my application.

I have a interface class IDemoService

public interface IDemoService
{
    bool CreateDemo(Demo demo);
    bool UpdateDemo(Demo demo);
    bool DeleteDemo(int id);
    Demo GetDemo(int id);
    Demo GetDemoServiceByName(string name);
    IEnumerable<Demo> GetAllDemo();
    void SaveRecord();
}

with using System.Reflection; I need to create reference like

IDemoService iDemoService;

I've tried this way so far:

var iDemoServiceClass = asm.GetTypes().Where(p =>
     p.Namespace == nameSpace &&
     p.Name == "IDemoService"
   ).ToList();
Type iDemoServiceClassType = iDemoServiceClass.FirstOrDefault();
var className = iDemoServiceClassType.Name;
var functionName = "Get" + iDemoServiceClassType + "ByName";
MethodInfo getMethod = demoServiceClassType.GetMethod(functionName);

var instanceCreate = Activator.CreateInstance(iDemoServiceClassType);//, null); //here I want to create reference instead instance
ParameterInfo[] parameters = getMethod.GetParameters();

if (parameters.Length > 0)
{
    object[] parametersArray = new object[] { "RequiredDemo" };
    var demoObj = getMethod.Invoke(instanceCreate, parametersArray);
}

Since it is interface so can't create instance but reference is possible. So, is it possible anyway to create reference using Reflection or any other way? Please help me right way. Thanks advance :D

You can't instantiate an interface, and so you can't create a reference to it. You need a concrete type implementing that interface, than you can use Activator.CreateInstance .

The point is that an interface is just a contract, not a real implementation; so for example you have no method bodies. Imagine the compiler letting you activate the interface, what is supposed to happen when you call a method without a body?

At least you need an empty class in the form DemoService:IDemoService , than you get a reference to it.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM