C # Getting common methods

When I need to pass a generic type, I can use the syntax

(Example: Of course, this is not a general method)

public void Sample(T someValue)
{
  ......
}

What is the advantage of an ad Sample<T>?

I mean

public void Sample<T> (T someValue)
{
    ......
}
+3
source share
4 answers

To make this work:

public void Sample(T someValue)
{
  ......
}

Type T must be declared in the system already. And the method will only accept type T or its derivatives.

Declaring this:

public void Sample<T> (T someValue)
{
    ......
}

you say that the method will accept any type that comes.

+4
source

General types and common methods are very different things. It looks like you have a generic type:

class SomeType<T> {
    public void Sample(T someValue) {...}
}

and discuss with him a general method:

class SomeType<T> {
    public void Sample<T>(T someValue) {...}
}

. , Sample, T "T, SomeType<T>". , Sample, T - "the T, Sample<T>". , T ( ) . , :

var obj = new SomeType<int>(); // here T for SomeType<T> is int
obj.Sample<decimal>(123.45M); // here T for Sample<T> is decimal

, ( Sample<T>) "T in SomeType<T>" - , generic .

( ), ( ):

class SomeType<T> {
    public void Sample<TActual>(TActual someValue) where TActual : T, new() {...}
}

.. - , T. .

+12

:

class SomeClass<T>
{
    public void Sample(T value)
    {
        // code goes here
    }
}

:

class SomeClass
{
    public void Sample<T>(T value)
    {
        // code goes here
    }
}

Sample T . T, generic type .

, , , factory :

public static class SomeFactory
{
    public static T CreateSomeObject<T>()
    {
        T result = Activator.CreateInstance<T>();
        // perform any extra initialization
        return result;
    }
}
+4

, . , . , .

+1

Source: https://habr.com/ru/post/1722795/


All Articles