Last active
March 20, 2017 21:40
-
-
Save luisdeol/7ff80e67c78e376aed5f03f6cce21fd7 to your computer and use it in GitHub Desktop.
Simple Console Application to show how to access private fields and their values through Reflection using C#.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Globalization; | |
using System.Reflection; | |
namespace TestingReflection | |
{ | |
public class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var calculator = new CostCalculator(); | |
var finalprice = calculator.CalculateFinalPrice(30); | |
Console.WriteLine($"Final Price: {finalprice.ToString(CultureInfo.InvariantCulture)}"); | |
var calc = typeof(CostCalculator); | |
var fields = calc.GetFields(BindingFlags.FlattenHierarchy|BindingFlags.NonPublic|BindingFlags.Public|BindingFlags.Static|BindingFlags.Instance); | |
foreach (var field in fields) | |
{ | |
Console.WriteLine($"Field: {field.Name} - Value: {field.GetValue(calculator)}"); | |
} | |
} | |
} | |
public class CostCalculator | |
{ | |
private readonly double _conversionFactor = 0.123; | |
private readonly int _fixedProfit = 10; | |
public double CalculateFinalPrice(int costToProduce) | |
{ | |
return _conversionFactor * costToProduce + _fixedProfit; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment