C# 泛型类型 : Warning from outer type

标签 c# generics types generic-type-argument

我有一个名为 UserController 的 Controller ,其泛型类型为 T:

public class UserController<T> : Controller
{    
}

然后,在这个类中,我有一个名为 Select() 的方法,具有通用类型:

public override T Select<T>(ushort id)
{
    // UserModel is just a Class where I is an integer typed property
    UserModel.I = 2;
    object result = UserModel.I;

    return (T)Convert.ChangeType(result, typeof(T));
    throw new NotImplementedException();
}

现在在另一个表单类中,我像这样访问这个方法:

// This is so far working
UserController<int> us = new UserController<int>(0);
label1.Text = us.Select<string>(0);

现在我收到这个警告:

Severity    Code    Description Project File    Line    Suppression State
Warning CS0693  Type parameter 'T' has the same name as the type 
parameter from outer type 'UserController<T>'

我不明白这里说的是什么:

Type parameter 'T' has the same name as the type 
parameter from outer type 'UserController<T>'

我在这里做错了什么?

最佳答案

如果您希望您的方法使用与您的类相同的类型进行参数化,则不要在方法名称中包含通用参数:

public override T Select(ushort id) /* Uses T from class */

但是,从您的其他示例来看,您似乎想要使用不同的类型 - 因此为参数使用不同的名称:

public override TInner Select<TInner>(ushort id)
{
    // UserModel is just a Class where I is an integer typed property
    UserModel.I = 2;
    object result = UserModel.I;

    return (TInner)Convert.ChangeType(result, typeof(TInner));


    throw new NotImplementedException();
}

(一般来说,尝试选择比 T 甚至 TInner 更好的名称 - 正如您应该为其他参数选择好的名称一样,尝试传达 类型参数名称中类型的用途

关于C# 泛型类型 : Warning from outer type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43135230/

相关文章:

c# - 使用 asp.net mvc beta 的强类型 actionlink?

c# - 可选的构造函数

C# Moq Entity Framework 6 数据上下文添加操作

haskell - 什么时候应该优先使用 TypeApplications 而不是 simple::signatures 或 ScopedTypeVariables?

java - 在Java中将 float 转换为字符串和字符串以 float

c# - 获取 sql server 中最后插入的以 id 作为主键并且是一个标识的行

java - 相同类型的通用多个参数

java - 具有构建器模式的通用对象

java - 泛型 "method does not override any method from its superclass"

objective-c - 在将属性移动到 .h 文件后,ARC 不允许将 Objective-C 指针隐式转换为 'int *'