简体   繁体   中英

How to Convert between Interface derived types?

In the most simplest for here is what I want to do:

interface InterfaceA
{
    string var1 { get; set; }
    string var2 { get; set; }
}

public class DerivedA : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DerivedB : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DoEverything
{
    InterfaceA A = new DerivedA();
    InterfaceA B = new DerivedB();

    A.var1 = "Test1";
    A.var2 = "Test2";

    B = ConvertObject<DerivedB>(A);

    write(B.var1 + ", " + B.var2);

    // This doesn't work, I would like it to though.
    public T ConvertObject<T>(object obj)
    {
        T result = (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });

        foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
        {
            if (propertyInfo.CanRead)
            {
                try
                {
                    object value = propertyInfo.GetValue(obj, null);
                    propertyInfo.SetValue(result, value, null);
                }
                catch { }
            }
        }

        return result;
    }
}

Right now I have to manually convert each property in my objects and when a new property is added I have to remember to go the conversion methods and add it. I would much prefer that this be done automatically.

Any help would be greatly appreciated.

thanks in advance

You could add a constructor to, say, DerivedB, that takes InterfaceA as an argument.

Eg

public class DerivedB : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
    public DerivedB(InterfaceA original)
    {
       var1 = original.var1;
       var2 = original.var2;
    }
}

Then you can use it as such:

public class DoEverything
{
    InterfaceA A = new DerivedA();

    A.var1 = "Test1";
    A.var2 = "Test2";

    InterfaceA B = new DerivedB(A);
    write(B.var1 + ", " + B.var2);
}

I guess I don't know what you're getting at. Why wouldn't you just declare constructors for DerivedA and DerivedB that take an InterfaceA for initialization? It would be simpler and more flexible, as each derived type would be responsible for initializing itself from the interface type. You could later add more types that implement the interface and they'd be usable by the other classes without any further changes.

您需要为两个派生类实现运算符重载

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