Recently I made a question about the generic return value, and found that:
1: Many people have made mistakes;
2: Many people have doubts about the significance of Using Generics as return values;
The questions are as follows:
"Writing a function requires that the input parameters and output results are generic ."
(PS: Someone pointed out in the comment that the question itself has a problem. A more appropriate description is: compile a function that requires that the type of input parameters and return values be generic parameters)
One of the typical incorrect answers:
public List<T> Function<T, U>(U parameter) { return new List<T>(); }
Typical error response 2:
void GetList<T>(ref T t1, out T t2) where T : List<T> { t2 = t1; }
Incorrect answer 1 is because many people think of a set when they think of generics. Yes, generic collections are an important application scenario of generics. However, what is the relationship between this and generics.
Many naturally come up with the second question, so what is the significance of Using Generics as the return value? Let's take a look at the example below:
public T GetActivatedServer<T>(NetIdentity netIdentity, string name) { string url = netIdentity.GetRemoteBaseUrl() + name; object service = Activator.GetObject(typeof(T), url); return (T)service; }
This is an example of remoting. The complete function is to return an instance of a remote object. If there is no generic type, we need to create a method for each remote object instance. With the generic type, this problem can be easily solved. (PS: This sentence is not correct. The comment points out that "when there is no generic type, we can also transfer a type and then force type conversion outside". Therefore, in this sentence, "solving this problem" should not mean less coding and more beautiful, but "Using Generics is efficient and type-safe ")
The called code is:
IClientContract client = RemoteObjectManager.Manager.GetActivatedServer<IClientContract>(target, "Client");
In addition, if you are familiar with LINQ, you will find that many methods in LINQ also use generic return values. Let's take a very useful set of methods, such as find, the following is the standard implementation of this method (. net internal code ):
public T Find(Predicate<T> match) { if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = 0; i < this._size; i++) { if (match(this._items[i])) { return this._items[i]; } } return default(T); }
Its standard call code is as follows:
MarshalByRefObject marshal = ObjRefList.Find(target => { return target.GetType() == obj.GetType(); });
Finally, we will attach the standard answer to this question:
TResoult GetT<TResoult, T1>(T1 t) { //some biz code return default(TResoult); }
From: http://www.cnblogs.com/luminji/archive/2010/11/08/1871782.html