【发布时间】:2021-04-15 08:17:07
【问题描述】:
当我写下面的代码时:
public interface IDoSomething<in TFrom>
{
void Process(TFrom content, string path);
void Process<TTemplate>(TFrom content, TTemplate template, string path);
}
public class ConcreteWorkA<string> : IDoSomething<string>
{
public void Process(string content, string path)
{
throw new NotImplementedException();
}
public void Process<TTemplate>(string content, TTemplate template, string path)
{
throw new NotImplementedException();
}
}
它不会在下面编译的地方编译,
public class ConcreteWorkB<String> : IDoSomething<String>
{
public void Process(String content, string path)
{
throw new NotImplementedException();
}
public void Process<TTemplate>(String content, TTemplate template, string path)
{
throw new NotImplementedException();
}
}
我也知道public class ConcreteWorkB : IDoSomething<String> 是正确的,但下面的代码可以工作。
public class COncreteWorkC<DataTable> : IDoSomething<DataTable>// Datatable from System.Data
{
public void Process(DataTable content, string path)
{
throw new NotImplementedException();
}
public void Process<TTemplate>(DataTable content, TTemplate template, string path)
{
throw new NotImplementedException();
}
}
由于字符串是字符串的别名,我希望它能够工作。还有为什么行为上的差异。 我正在使用 VS 2019,.Net 5。
我得到的错误是
- 语法错误,应为“,”
- 需要标识符
编辑:评论和接受的答案说明 String/DataTable 被视为泛型类型参数而不是具体类型,因此字符串是错误。
【问题讨论】:
-
你希望
DoesSomething<string> : IDoSomething<string>{}的行做什么?请注意,DoesSomething<String> : IDoSomething<String>{}也不编译。如果您尝试指定类声明,请明确说明。 minimal reproducible example 真的会帮助你的问题。 -
@JonSkeet:
DoesSomething<String>实际上编译,似乎编译器将String视为只是一个通用参数类型名称。 dotnetfiddle.net/IzSbUg -
如果是
class DoesSomething<string> : IDoSomething<string> {},那么第一个string是您的泛型类型的占位符名称,因此不允许使用它,因为它会与built-in typestring混淆。我不能 100% 确定您是否认为您指定类型应该是string,或者您是否知道这是您的泛型类型参数的 name。 -
请参阅this question。您误解了
class ConcreteWorkA<string> : IDoSomething<string>和class COncreteWorkC<DataTable>声明的内容。 -
@anshu:提供一个最小的完整示例远非信息过载。不需要太多就可以清楚地表明您正在尝试编写类声明。您的编辑仍然不完整,因为现在您还没有在任何地方声明
IDoSomething<T>。请阅读codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question