Skip to main content

Type

public class PropTest1
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
}
public class PropTest0
{
public string Prop0 { get; set; }
public PropTest1 Prop { get; set; }
}

IsBuildInType/IsBaseType

note

判断是否基本数据类型

Boolean,Byte,SByte,Char,Decimal,Double,Single,Int32

UInt32,IntPtr,UIntPtr,Int64,UInt64,Int16,UInt16,String,......

int intValue = 2333;
long longValue = 2333;
double doubleValue = 2333.2333;
string stringValue = "23333";
bool boolValue = true;
...

intValue.IsBuildInType(); // True
longValue.IsBuildInType(); // True
doubleValue.IsBuildInType(); // True
stringValue.IsBuildInType(); // True
boolValue.IsBuildInType(); // True
boolValue.IsBaseType(); // True
...
caution

并没有使用类型的 IsPrimitive 进行判断, 因为 DateTime,Guid 等也被我当成 BaseType 了

所以实际使用的时候可能会有奇奇怪怪的问题

PropNames(获取属性的名称)

var props = typeof(PropTest1).PropNames();
// {"Prop1", "Prop2", "Prop3"}
props = new PropTest0().PropNames();
// {Prop0", "Prop"}
props = new PropTest0().PropNames(1);
// {"Prop0", "Prop.Prop1", "Prop.Prop2", "Prop.Prop3"}
props = typeof(PropTest0).PropNames(0);
// {Prop0", "Prop"}
tip

使用递归实现, 可针对嵌套类型设定递归深度

默认深度为 0

GetValue(获取属性Value)

var obj = new PropTest1
{
Prop1 = "1",
Prop2 = "2",
Prop3 = "3",
};
obj.GetValue("Prop1"); // "1"
caution

只做了获取公共属性值的部分,没有获取私有字段的功能,后期可能会考虑增加

tip

可以获取嵌套类型的属性值

var obj = new PropTest1
{
Prop1 = "1",
Prop = new(){
Prop1 = "1.1",
}
};
obj.GetValue("Prop.Prop1"); // "1.1"

SetValue(设置属性Value)

var data = new PropTest1 { Prop1 = "1" };
data.SetValue("Prop1", "233");
// data.Prop1 == "233"
caution

只做了修改公共属性值的部分,没有修改私有字段的功能,后期可能会考虑增加

tip

可以设置嵌套类型的属性值

var obj = new PropTest1
{
Prop1 = "1",
Prop = new(){
Prop1 = "1.1",
}
};
obj.SetValue("Prop.Prop1", "1.2");

GetAnonymousValue(获取匿名类型的属性值)

var obj = new
{
Index = 233,
Name = "",
Item = new
{
Index = 0,
Name = "2333"
}
};
(int)obj.GetValue("Index"); // 233
(int)obj.GetValue("Item.Name"); // "2333"

SetAnonymousValue(设置匿名类型的属性值)

var obj = new
{
Index = 0,
Name = "",
Item = new
{
Index = 0,
Name = ""
}
};
obj.SetAnonymousValue("Index", 233);
obj.SetAnonymousValue("Item.Index", 233);
caution

虽然做出来了, 但感觉可能并没有什么用

AttrValues

note

获取类属性上的 Attribute

...
sealed class UnitTestAttribute : System.Attribute
{
readonly string _field;

public UnitTestAttribute(string field)
{
_field = field;
}
public string Field
{
get { return _field; }
}
}
public class AttrTest
{
[UnitTest("123")]
public string Prop1 { get; set; }
[UnitTest("233")]
public string Prop2 { get; set; }
}
var attrValues = typeof(AttrTest).AttrValues<UnitTestAttribute>();
attrValues.Count; // 2
attrValues.First().Value.Field; // "123"
attrValues.Last().Value.Field; // "233"