嗨 我尝试创建动态方法
public void SetId(Guid id) { Id = id; }我试试,但我是私人套装
var DynamicMethod = new DynamicMethod( Division, typeof ( void ), new 输入[] { typeof (Guid)},entityType.Module ); var il = DynamicMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Callvirt,entityType.GetProperty( Id)。GetSetMethod ()); il.Emit(OpCodes.Ret);我该怎么做 我尝试过: DynamicMethod = new DynamicMethod(Division,typeof(void),new Type [] {typeof(Guid)} ,entityType.Module); var il = DynamicMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il。 Emit(OpCodes.Callvirt,entityType.GetProperty(Id)。GetSetMethod()); il.Emit(OpCodes.Ret);
解决方案如果你有这个: 使用系统; 命名空间 YourNameSpace { public abstract class PersonBase { public PersonBase(Guid id) { Id = id; } // 在ctor或ResetID方法之外隐藏/ span> 内部 Guid ID { private 设置; get ; } 内部 void ResetID(Guid id) { Id = id; } } public class 人员: PersonBase { public Person(Guid id): base (id) {} public Person(): base (Guid.Empty) {} } }
你可以这样做来使用'Activator.CreateInstance,并传递一个值'Guid参数:
Person somePerson = Activator.CreateInstance( typeof (Person), new 对象 [] {Guid.NewGuid()}) as Person; $ p $希望这很有帮助。如果你在运行时做了很多花哨的.NET对象组合,我建议你研究T4的使用:[ ^ ]感谢重播。示例代码如下 public 摘要 类基础 { public readonly Id; } public class 人:基数 {}
我创建人物实例,如Activator.CreateInstance< t>() i想要设置Id。有什么建议吗? 谢谢
Hi I try to create dynamic method as
public void SetId(Guid id) { Id = id; }I try but Id is private set
var DynamicMethod = new DynamicMethod("Division", typeof(void), new Type[] { typeof(Guid) }, entityType.Module); var il = DynamicMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Callvirt, entityType.GetProperty("Id").GetSetMethod()); il.Emit(OpCodes.Ret);how can i do this What I have tried: DynamicMethod = new DynamicMethod("Division", typeof(void), new Type[] { typeof(Guid) }, entityType.Module); var il = DynamicMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Callvirt, entityType.GetProperty("Id").GetSetMethod()); il.Emit(OpCodes.Ret);
解决方案 If you have this:using System; namespace YourNameSpace { public abstract class PersonBase { public PersonBase(Guid id) { Id = id; } // hide from exposure outside 'ctor or 'ResetID method internal Guid Id { private set; get; } internal void ResetID(Guid id) { Id = id; } } public class Person : PersonBase { public Person(Guid id) : base(id) { } public Person() : base(Guid.Empty) { } } }You can do this to use 'Activator.CreateInstance, and pass a value for the 'Guid parameter:
Person somePerson = Activator.CreateInstance(typeof (Person), new Object[]{Guid.NewGuid()}) as Person;Hope that's helpful. If you are doing a lot fancy composition of .NET objects at run-time, I suggest you research the use of T4: [^]
Thanks for replay. Sample code is below public abstract class Base { public readonly Id; } public class Person : Base { }I create Person Instance like Activator.CreateInstance<t>() i want to set Id. Any suggestion ? thanks
更多推荐
何可以创建动态方法c#
发布评论