在运行时将属性的属性从一个实例复制到另一个实例(不同类型)

Omu*_*Omu 2 c# reflection reflection.emit

假设我有2个这样的类:

public class Foo
{
[Required]
public string Name {get;set;}
}

public class Bar 
{
// put here [Required] at run-time
public string Name {get;set;}
}

var foo = new Foo();
var bar = new Bar();
//copy the required from foo to bar
Run Code Online (Sandbox Code Playgroud)

是否可以在运行时将属性从foo复制到bar?

dtb*_*dtb 8

属性未附加到实例 - 它们附加到类型定义.

虽然您可以使用反射在运行时创建新类型,但您无法更改现有的类型定义.