How to Create Generic Functions

Asked 2 years ago, Updated 2 years ago, 33 views

Hello.

I would like to create a method that retrieves data from XML in LINQ, stores the data in each type, and returns it.
However, I can't do it at all when they tell me to specify the type, such as "Null acceptable type is not allowed."
Can't I create a generic function using the one I made myself?

*PropertiesInfo can handle the process of creating the contents of each instance, so this is fine.

■ Table Type

class offices {
    int No;
    String Data;
}

class Workers {
    int No;
    String FullName;
}

■ Code

/**Code 1**/
public TFunc<T>(Table) where T:struct{
    // This includes storing data from LINQ in each type (T).
    return(T)Table;
}

エラーError:
 CS0453 type 'T' is a generic parameter 'T',
      or
for use as the method 'Nullable'       Must be a null non-permissive value type

/**Code 2**/
public Nullable<T>Func<T>(T?Table) where T:struct{
    // This includes storing data from LINQ in each type (T).
    return(T)Table;
}

エラーError:
 The CS0411 method 'Func(T?)' type argument cannot be inferred from usage.
      Specify type arguments explicitly

c#

2022-09-30 17:57

2 Answers

CS0453 type 'T' is a generic parameter 'T',
      or
for use as the method 'Nullable'       Must be a null non-permissive value type

This is probably an error message that occurs when you use a null acceptable type such as Nullable<T> (=T?) inside the signature method publicTFunc<T>(Table)<

The CS0411 method 'Func(T?)' type argument cannot be inferred from usage.
      Specify type arguments explicitly

This is a type inference failure on the caller of Func.The code in the question is hard to imagine because there is no ambiguity in the type, but it occurs when you call Func() to Func<T>(T?a=null)where T:structure.Resolve it by specifying the type you normally use, such as Func<int>().

The Offices is a class and therefore does not meet the struct constraint and cannot be used as a type argument for Func.The Offices type itself allows null, so you don't have to use Offices?.Therefore, the error caused by this is displayed.

Perhaps what you really need is an interface, not a structure.
Define an interface common to the two types and implement a method to accept it.new()If you do not use constraints, it does not have to be generic.


2022-09-30 17:57

If you don't write Func<T>(...), no matter how much you write T, it won't become generic!
The Linq method should be written in the same way, so please check it out.

Also, where T:structure does not accept classes, so you can delete them.


2022-09-30 17:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.