What does Method mean?

后端 未结 5 569
北海茫月
北海茫月 2021-01-31 07:57

I\'ve seen this syntax a couple times now, and it\'s beginning to worry me,

For example:

iCalendar iCal = new iCalendar();
Event evt = iCal.Create

        
相关标签:
5条回答
  • 2021-01-31 08:21

    It's calling a generic method - so in your case, the method may be declared like this:

    public T Create<T>()
    

    You can specify the type argument in the angle brackets, just as you would for creating an instance of a generic type:

    List<Event> list = new List<Event>();
    

    Does that help?

    One difference between generic methods and generic types is that the compiler can try to infer the type argument. For instance, if your Create method were instead:

    public T Copy<T>(T original)
    

    you could just call

    Copy(someEvent);
    

    and the compiler would infer that you meant:

    Copy<Event>(someEvent);
    
    0 讨论(0)
  • 2021-01-31 08:21

    It is a generic method that implements the Factory Method pattern.

    0 讨论(0)
  • 2021-01-31 08:33

    This syntax is just applying generics to a method. It's typically used for scenarios where you want to control the return type of the method. You will find this kind of syntax a lot in code that uses a IoC framework.

    0 讨论(0)
  • 2021-01-31 08:39

    It's a Generic Method, Create is declared with type parameters, and check this links for more information:

    • An Introduction to C# Generics
    • Generics (C# Programming Guide)
    • Generic Methods
    0 讨论(0)
  • 2021-01-31 08:43

    It's the way you mention a generic method in C#.

    When you define a generic method you code like this:

    return-type MethodName<type-parameter-list>(parameter-list)
    

    When you call a generic method, the compiler usually infers the type parameter from the arguments specified, like this example:

    Array.ForEach(myArray, Console.WriteLine);
    

    In this example, if "myArray" is a string array, it'll call Array.ForEach<string> and if it's an int array, it'll call Array.ForEach<int>.

    Sometimes, it's impossible for the compiler to infer the type from the parameters (just like your example, where there are no parameters at all). In these cases, you have to specify them manually like that.

    0 讨论(0)
提交回复
热议问题