开发者

Casting between similar types in C#

开发者 https://www.devze.com 2023-03-27 10:02 出处:网络
I have two开发者_StackOverflow社区 types that have the same members, but different names. Is there an easy or standard way to cast between them, or do I have to do some serious hacking with reflection

I have two开发者_StackOverflow社区 types that have the same members, but different names. Is there an easy or standard way to cast between them, or do I have to do some serious hacking with reflection?


You could create an interface that describes both of the types. Make each type implement the interface, then use the interface instead of a specific type when working in code that can deal with either type.


You have to either do hacking with reflection (I have a PropertyCopy class in MiscUtil which can help) or use dynamic typing from C# 4.

As far as .NET is concerned, these are completely separate types.


This is far from perfect, but I use this extension method to copy properties with the same name between objects based on a common interface

public static T CopyTo<T>(this T source, T target) where T : class 
{
    foreach (var propertyInfo in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
    {
        propertyInfo.SetValue(target, propertyInfo.GetValue(source, null), null);
    }

    return target;
}

Usage is something like

var internationalCustomer = new InternationalCustomer();
var customer = (Customer)internationalCustomer.CopyTo<ICustomer>(new Customer());

where InternationalCustomer and Customer both have to have implemented ICustomer.

0

精彩评论

暂无评论...
验证码 换一张
取 消