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; }
public bool Enabled; //是否有效 public bool Live; //是否是旧数据 public int WebID; //网ID public int Kind; //数据类型(1-单独赢,2-单位置,3-两个都有) 这样的类属性似乎不能用
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); } } }
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;
}
public bool Live; //是否是旧数据 public int WebID; //网ID
public int Kind; //数据类型(1-单独赢,2-单位置,3-两个都有)
这样的类属性似乎不能用
{
[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);
}
}
}