由于我不确定我能够准确地命名/制定一切,所以我会使用一个天真的例子。让我们来看看:
class Base<T>
{
...
}
/*
* Please note the Derived is not generic, only derives from generic class
*/
class Derived : Base<SomeType>
{
/*
* Here, I would like to use SomeType's "generic name" (like the T in the Base),
* so it might look like:
*/
Base.T field1; // This would translate to 'SomeType field1' for this particular case
...
}
C#
语法中是否有任何方法可以访问Base.T
?
我当然知道如果我们使Derived
也是通用的,我们可以将其类型参数传递给Base
并在{{1}中使用它}} 的
修改
请将此视为一个理论问题,在此我想确定,是否有Derived
语法方式来达到用于&#34;模板化&#34;的符号类型名称。在基类中。最初的动机可能是:如果开发人员以C#
取代Derived
的方式修改Base<SomeType>
类,他还需要在Base<OtherType>
正文中的所有出现时替换它。对于这些情况,Derived
与SomeType
兼容,并且还有一个可用的符号名称(如Base.T),没有其他工作要做。 (是的,我知道,我们有自动重构工具......只是一个问题......)
答案 0 :(得分:0)
我认为可以解决您的问题:
class Base<T>
{
protected T field1;
}
/*
* Please note the Derived is not generic, only derives from generic class
*/
class Derived : Base<string>
{
/*
* Here, I would like to use SomeType's "generic name" (like the T in the Base),
* so it might look like:
*/
//[not necessary]
//Base.T field1; // This would translate to 'SomeType field1' for this particular case
public Derived()
{
field1 = "hello world";
}
}
答案 1 :(得分:0)
class Base<T>
{
protected T SomeField;
}
class Derived : Base<SomeType>
{
private Type GetSomeType(bool asConstructed)
{
// here SomeField is SomeType because Derived is a constructed type.
if (asConstructed)
return SomeField.GetType(); // of course, if SomeField is null, use GetField instead
// However, you can get the T if you really want:
return this.GetType().BaseType.GetGenericTypeDefinition().GetGenericArguments()[0];
}
}