Вместо
int[] values = (int[]) typeof(DialogueManager).GetProperty(fixedName).GetValue(this, null);
вы можете попытаться использовать
int[] values = (int[]) ((dynamic) this).fixedName;
, который должен работать, поскольку ваше свойство fixedname
является общедоступным свойством экземпляра.
Или, еще лучше, переосмыслить, почему вам нужно определять имена свойств во время выполнения?Разве простой
if(textNum == 1) return this.consequences1;
else if(textNum == 2) return this.consequences2;
// ...
не подойдет?
РЕДАКТИРОВАТЬ
Я просто перечитал ваш вопрос.Ваш вопрос о том, что Console.WriteLine
печатает System.Int32[]
, когда вы хотите, чтобы он печатал действительные значения массива?Если это так, вы можете использовать
foreach(int v in values) // where values is your int[]
{
Console.WriteLine(v);
}
, что дает
1
2
3
, или вы можете использовать
Console.WriteLine("[" + String.Join(",", values) + "]");
, что дает
[1,2,3]
РЕДАКТИРОВАТЬ 2 Ниже я написал код, который, я думаю, выполняет вашу задачу.Основная логика происходит в методе GetPropertyValueSafe
, который отвечает за проверку того, существует ли запрошенное свойство, и, если это так, получает значение свойства как указанный тип.
public class DialogueManager
{
private static IReadOnlyCollection<PropertyInfo> AllProperties = typeof(DialogueManager).GetProperties();
private T GetPropertyValueSafe<T>(string propertyName)
{
PropertyInfo thePropertyInfo = DialogueManager.AllProperties.SingleOrDefault(x => x.Name == propertyName);
if (thePropertyInfo is null)
{
throw new InvalidOperationException($"Type {this.GetType()} has no property {propertyName}.");
}
return (T) thePropertyInfo.GetValue(this);
}
private string ArrayToString<T>(T[] array)
{
return String.Join(", ", array);
}
public string GetText(int currentText)
{
return this.GetPropertyValueSafe<string>("text" + currentText);
}
public string GetTextChoices(int textNum)
{
return this.GetPropertyValueSafe<string>("choices" + textNum);
}
public int[] GetChoicesConsequences(int textNum)
{
return this.GetPropertyValueSafe<int[]>("consequences" + textNum);
}
public string text1 { get; set; } = "Text 1";
public string choices1 { get; set; } = "Choice 1";
public int[] consequences1 { get; set; } = new int[] { 1, 2 };
public string text2 { get; set; } = "Text 2";
public string choices2 { get; set; } = "Choice 2";
public int[] consequences2 { get; set; } = new int[] { 1, 2, 3 };
public static void Main(string[] args)
{
DialogueManager d = new DialogueManager();
Console.WriteLine(d.ArrayToString(d.GetChoicesConsequences(1)));
Console.WriteLine(d.GetText(1));
Console.WriteLine(d.GetTextChoices(1));
Console.WriteLine(d.ArrayToString(d.GetChoicesConsequences(2)));
Console.WriteLine(d.GetText(2));
Console.WriteLine(d.GetTextChoices(2));
Console.ReadLine();
}
}
Код выше дает
> 1, 2
> Text 1
> Choice 1
> 1, 2, 3
> Text 2
> Choice 2