mercredi 6 octobre 2021

How to get value from a library for usage by reflection?

I try to make a currency converter by c#. At first, I have made a library that will get all the exchange rates from an API

public class CurrencyRate
{
    public string Disclaimer { get; set; }
    public string License { get; set; }
    public int Timestamp { get; set; }
    public string Base { get; set; }
    public IDictionary<string, double> Rates { get; set; } 
    public void getRate()
    {
        
        string url = "https://openexchangerates.org/api/latest.json?app_id=69cb235f2fe74f03baeec270066587cf";

        WebClient myClient = new WebClient();
        string txt = myClient.DownloadString(url);

        var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
        var latest = JsonSerializer.Deserialize<CurrencyRate>(txt, options);
        //Console.WriteLine(latest.Rates.First());

        Console.WriteLine(string.Join("\n", latest.Rates.Select(rate => $"{rate.Key},{rate.Value}")));

    }
}

And I have my main that using reflection to print all the values on the screen

static void Main(string[] args)
    {
        Assembly myAssembly = Assembly.LoadFile(System.IO.Path.GetFullPath("C:/../../../../../../../../../RateLib.dll"));
        Type rateType = myAssembly.GetType("RateLib.CurrencyRate");
        object myRateRef = Activator.CreateInstance(rateType);
        MethodInfo getRate = rateType.GetMethod("getRate");
        getRate.Invoke(myRateRef, null);
       
    }

But the real purpose is I want to use the reflection not to print the value on the screen, but to get the value and calculating the money exchange. I know since my method in the library is void so it won't return anything, and I try to change it to something like public string getRate(string rate) but then I don't know what thing I should return with it





Aucun commentaire:

Enregistrer un commentaire