When do you use reflection? Patterns/anti-patterns

前端 未结 17 2202
旧时难觅i
旧时难觅i 2020-12-02 09:58

I understand the reflection API (in c#) but I am not sure in what situation would I use it. What are some patterns - anti-patterns for using reflection?

17条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 10:37

    I personaly don't use it a lot. I tend to use it when I don't have a different way to code something.

    Here is an simple example:

    public static void LogException(Exception exc, string source)
    {
        try
        {
            // Logic for logging exceptions
        }
        catch(Exception ex)
        {
            //If logging fails  for some reason 
            //then we still log it using reflection
            LogException(ex, "Error while logging an exception");
        }
    }
    

提交回复
热议问题