Generic constructors and reflection

前端 未结 4 956
说谎
说谎 2021-02-14 17:25

Is it possible to see which constructor was the generic one?

internal class Foo
{
  public Foo( T value ) {}
  public Foo( string value ) {}
}

var cons         


        
4条回答
  •  无人共我
    2021-02-14 17:35

    Can you explain a bit more what you're trying to accomplish, when you say you want to call the concrete constructor? I'm just curious if there's another way to solve your issue without having to detect whether the constructor contains generic parameters.

    I'm thinking chaining constructors or building logic into the generic one to behave a certain way if the parameter passed in is a string, such as:

        static void Main(string[] args)
        {
            Console.WriteLine(new Foo("myValue").IsValueAString);
            Console.WriteLine(new Foo(1).IsValueAString);
            Console.ReadLine();
        }
    
        public class Foo
        {
            public bool IsValueAString = false;
            public Foo(T value) {
                if (value is string)
                {
                    IsValueAString = true;
                }
            }
        }
    

    Another option would be to create a concrete implementation of Foo, something like:

    internal class Foo
    {
        ...
    }
    internal class MyFoo : Foo
    {
        ...
    }
    

    and embed any specific logic in the constructor of the descendant. All kinds of options down this path are possible so you can avoid having to reflect the info out of that one class.

提交回复
热议问题