c# 2 个结构相同的类赋值怎么做好,A类和B类不有任何继承关系,他们属性名相同,怎么给他们互相赋值呢

csdsuper 2011-04-18 07:25:12
c# 2 个结构相同的类赋值怎么做好
A类和B类不有任何继承关系,他们属性名相同,怎么给他们互相赋值呢
...全文
365 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
csdsuper 2011-04-19
  • 打赏
  • 举报
回复
对于这一个方法,如果是类中有其它类对象的就不能用了,不过还是感谢你的
[Quote=引用 9 楼 whycom 的回复:]
C# code
namespace hardcopy
{
[StructLayout(LayoutKind.Sequential)]
public class A {
public int a;
public A() { a = 0; }
}
[StructLayout(LayoutKind.Sequential)]
……
[/Quote]
whycom 2011-04-18
  • 打赏
  • 举报
回复
namespace hardcopy
{
[StructLayout(LayoutKind.Sequential)]
public class A {
public int a;
public A() { a = 0; }
}
[StructLayout(LayoutKind.Sequential)]
public class B
{
public int a;
public B() { a = 0; }
}
class Program
{
static void Main(string[] args)
{
A a1 = new A();
a1.a = 100;
B b1=new B();
IntPtr p = Marshal.AllocCoTaskMem(Marshal.SizeOf(a1));
Marshal.StructureToPtr(a1, p, true);
Marshal.PtrToStructure(p,b1);
}
}
}
csdsuper 2011-04-18
  • 打赏
  • 举报
回复
public bool Enabled; //是否有效
public bool Live; //是否是旧数据

public int WebID; //网ID
public int Kind; //数据类型(1-单独赢,2-单位置,3-两个都有)
这样的类属性似乎不能用
Hamber_Bao 2011-04-18
  • 打赏
  • 举报
回复
楼主考虑的太多了,直接硬编码就可以了。

还有一个问题,就是既然两个类结构相同,为什么还要有两个类呢,直接写一个类就可以了。
winner2050 2011-04-18
  • 打赏
  • 举报
回复
又不是什么高科技的功能,想那么复杂干吗?

直接硬编码完事。
Cylan 2011-04-18
  • 打赏
  • 举报
回复

public L SetProperties<T, L>(T t) where L : new()
{
if (t == null)
{
return default(L);
}
System.Reflection.PropertyInfo[] propertiesT = typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
System.Reflection.PropertyInfo[] propertiesL = typeof(L).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (propertiesT.Length != propertiesL.Length || propertiesL.Length == 0)
{
return default(L);
}
L setT = new L();
foreach (System.Reflection.PropertyInfo itemL in propertiesL)
{
foreach (System.Reflection.PropertyInfo itemT in propertiesT)
{
if (itemL.Name == itemT.Name)
{
object value = itemT.GetValue(t, null);
itemL.SetValue(setT, value, null);
}
}
}
return setT;
}
xiaoyuzi 2011-04-18
  • 打赏
  • 举报
回复
你要用聪明点的方法么,那就反射
cnxry 2011-04-18
  • 打赏
  • 举报
回复
或许是我没明白楼主的意思
首先楼主的问题就问得很怪,为什么要有2个结构相同的类?
如果结构完全一样,又不需要任何关系,那一个类实例化2次不就得到了你要的?那直接用 = 赋值就可以

如果非要这样的话也只有1楼说的依次赋值了
csdsuper 2011-04-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 peter200694013 的回复:]
单独定义方法 依次对属性赋值...
[/Quote]
这是最笨的方法了,我也知道,但是还有更好的吗?
Peter200694013 2011-04-18
  • 打赏
  • 举报
回复
单独定义方法 依次对属性赋值...

110,580

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧