Install all class members that implement an interface from an object of type interface without a lot of write code in C #

This may seem a little complicated, but I will try to explain it clearly.

Is this possible in C # if I have a long interface:

public interface IInterface
{
    bool interface_1;
    bool interface_2;
    bool interface_3;
    bool interface_4;
    bool interface_5;
    ...
}

And the class that implements the interface

public class MyClass : IInterface
{
    ...
}

Imagine I have an IInterface object myInterface, is there a way to create a MyClass object myClass and set all myClass fields to one of myInterface without setting all the fields one after the other. For instance:

IInterface myInterface;
MyClass myClass;
myClass.SetIInterface(myInterface);
+3
source share
5 answers

Imagine I have an IIterter myInterface object, is there a way to create a MyClass myClass object and set all myClass fields with one of myInterface

. , , . , , , . . , , - , , , , .

. .

+2

, , . typeof(IInterface).GetProperties() ( ), , , (, PropertyInfo.GetValue() PropertyInfo.SetValue()).

+1

, . , IInterface MyClass:

public interface IInterface
{
    bool interface_1 { get; set; }
}

public class MyClass : IInterface
{

}

public class ReflectionHelper
{
    private MyClass CreateByCopy(IInterface instance)
    {
        MyClass obj = new MyClass();
        foreach (PropertyInfo property in typeof( IInterface ).GetProperties())
        {
            property.SetValue( property, property.GetValue( instance, null ), null );
        }

        return obj;
    }
}

, , . , . , .

+1

- : ( , ), AutoMapper ( )

+1

, . SetIInterface() (/ ) . , MyClass IInterface.

0

Source: https://habr.com/ru/post/1766996/


All Articles