简体   繁体   中英

Binding two objects of different classes but with similar properties

Is it possible in C# to bind two objects of different classes but with similar properties?

For Example:

class Program
{
    static void Main(string[] args)
    {
        test t = new test();

        test2 t2 = new test2();
    }
}

public class test
{
    public int Number { get; set; }
}

public class test2
{
    public int Number { get; set; }
}

So is it possible to say t = t2 somewhow?

You can have both classes implement an interface, if you don't care about what implementation of the interface is used.

For example:

class Program
{
    static void Main(string[] args)
    {
        INumber t = new test();

        INumber t2 = new test2();
    }
}

public class test : INumber
{
    public int Number { get; set; }
}

public class test2 : INumber
{
    public int Number { get; set; }
}

public interface INumber
{
    int Number { get; set; }
}

An interface is a sort of contract, that provides a definition of what properties and methods an implementing class must define. You can read more on interfaces here .

When your classes implement a shared interface, you're able to to implicitly convert one type into another type, such as in the example above.

Without the addition of extra code, no, you cannot do that.

Even though they are "similar" they are regarded as totally different types by the compiler, and cannot be assigned to each other.

Now, you can include an implicit operator on one (or both) in order to allow implicit casting between the two.

public class test
{
    public static implicit operator test(test2 t)
    {
        return new test(tt.Number);
    }

    public static implicit operator test2(test t)
    {
        return new test2(t.Number);
    }

   public int Number { get; set; }
}

But that is as close as you can get to supporting that syntax.

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