下边分别是访问一个类的字段,属性,还有方法通过反射来获取对应的东西,下面就附上详细的代码
```csharp
public void ReflectionClassGetFieldsInfoFunction<T>() where T : new()
{
T myInstance = new T();
Type myType = typeof(T);
try
{
FieldInfo[] myFields = myType.GetFields(BindingFlags.Public | BindingFlags.Instance);
for(int i=0;i<myFields.Length;i++)
{
int index = i;
if (myFields[index].GetValue(myInstance) is int)
{
string name = myType.Name.ToLower() + "." + myFields[index].Name + "=" + ReturnIntProperty();
Debug.Log("FieldIntName:" + name);
}
else if(myFields[index].GetValue(myInstance) is bool)
{
string name = myType.Name.ToLower() + "." + myFields[index].Name + "=" + ReturnTrueOrFalseProperty();
Debug.Log("FieldBoolName:" + name);
}
else if(myFields[index].GetValue(myInstance) is float)
{
string name = myType.Name.ToLower() + "." + myFields[index].Name + "=" + ReturnFloatProperty();
Debug.Log("FieldfloatName:" + name);
}
else
{
string name = myType.Name.ToLower() + "." + myFields[index].Name + "=" + "\"" + ReturnStringProperty() + "\"";
Debug.Log("Fieldsstringname:" + name);
}
}
}
catch(Exception e)
{
Debug.Log("捕获奇怪的异常");
}
}
public void ReflectionClassGetPropertyInfoFunction<T>() where T:new()
{
T hello = new T();
Type type = hello.GetType();
PropertyInfo[] propertyInfo = type.GetProperties();
Debug.Log("Class类:" + type.Name);
Debug.Log("PropertyInfoCount:" + propertyInfo.Length);
foreach (PropertyInfo Info in propertyInfo)
{
object value = Info.GetValue(hello);
if (value is int)
{
string name =type.Name.ToLower()+"."+Info.Name + "=" + ReturnIntProperty();
Debug.Log("intname:" + name);
}
else if (value is double)
{
string name = type.Name.ToLower()+"."+Info.Name + "=" + ReturnDoubleProperty();
Debug.Log("doublename:" + name);
}
else if (value is float)
{
string name =type.Name.ToLower()+"."+ Info.Name + "=" + ReturnFloatProperty();
Debug.Log("floatname:" + name);
}
else if(value is bool)
{
string name = type.Name.ToLower()+"."+Info.Name + "=" + ReturnTrueOrFalseProperty();
Debug.Log("boolname:" + name);
}
else
{
string name = type.Name+"."+Info.Name + "=" + "\"" + ReturnStringProperty() + "\"";
Debug.Log("stringname:" + name);
}
}
}