简体   繁体   中英

The type 'T1' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'

Here iam getting error

The type 'string' must be a non-nullable value type in order to use it as parameter 'T1' in the generic type or method 'GetDataKeyValue(System.Web.UI.WebControls.GridView, int, string)'

String Process = GetDataKeyValue<String>(gvTargetRate, RowIndex, "Process");

Here iam getting error

The type 'T1' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

private Nullable<T> GetDataKeyValue<T>(GridView gv, int RowIndex, T column)
{
    if (column == null)
        return default(T);

    return (T)gv.DataKeys[RowIndex].Values[column];
}

You can't create a Nullable<> out of any type. As the compiler tells you, you can only do that for value types. Since the method isn't restricted to any type, it can't say for sure you won't pass it, let's say, an object.

What you want isn't possible, actually, as explained in this question and its answer .

And by the way, T isn't a nullable type by definition, so default(T) will become a non-null value in the case of value types. string is on object, so it can be null without the use of Nullable<T> .

The Nullable type requires that T is a non-nullable value type, for example int or DateTime. Reference types like string can already be null. There would be no point in allowing things like Nullable so it is disallowed.

more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM