C# 动态改变属性类型

Ant*_*eia 1 c# types properties class type-conversion

我正在尝试动态更改代码中的属性类型,例如,在下面的Person类中,如何将属性名称类型从 bool 更改为 string?

public class Person
{     
    public bool name;    
}
Run Code Online (Sandbox Code Playgroud)

Jua*_*uan 5

如果您想在运行时执行此操作,您有不同的选择。他们中有一些:

1) 创建属性对象并在使用它时检查类型:

public class Person
{     
    public object Name;    
}
Run Code Online (Sandbox Code Playgroud)

2) 为 Person 创建一个泛型类型,允许您为不同类型定义该类的不同实例:

public class Person<T>
{     
    public T Name;    
}

var boolPerson = new Person<bool>();
boolPerson.Name = true;
var stringPerson = new Person<string>();
stringPerson.Name = "aString";
Run Code Online (Sandbox Code Playgroud)

但是,您应该解释为什么要这样做,因为可能有更好的解决方案。