问题描述
是否可以执行以下操作(如果这样,我似乎无法使其正常工作..................................
如果推断出类型(因为它被忽略了),那是什么问题?
private void GetGenericTableContent<T>(ref StringBuilder outputTableContent, T item)
{
outputTableContent.Append("<td>" + item.SpreadsheetLineNumbers + "</td>");
}
// 'item' is either DuplicateSpreadsheetRowModel class or SpreadsheetRowModel class
使用上面的代码,我得到以下错误:
否,这是不可能的.泛型类型必须在编译时知道.想一想,编译器如何才能知道保证T
类型具有SpreadsheetLineNumbers
属性?如果T
是原始类型(例如int
或object
)怎么办?
是什么阻止了我们使用ref _, 999
参数调用方法(此处T为int)?
仅当我们添加一个包含此属性的接口时,它才起作用:
public interface MyInterface
{
string SpreadsheetLineNumbers { get; set; }
}
让您的类从该接口继承
public class MyClass : MyInterface
{
public string SpreadsheetLineNumbers { get; set; }
}
然后我们可以使用泛型类型约束让编译器知道T类型是从此接口派生的,因此它必须包含并实现其所有成员.
private void GetGenericTableContent<T>(ref StringBuilder outputTableContent, T item)
where T : IMyInterface // now compiler knows that T type has implemented all members of the interface
{
outputTableContent.Append("<td>" + item.SpreadsheetLineNumbers + "</td>");
}
Is it possible to do the following (If so I can't seem to get it working.. forgoing constraints for the moment)...
If the type (because it's ommitted) is inferred, what's the problem?
private void GetGenericTableContent<T>(ref StringBuilder outputTableContent, T item)
{
outputTableContent.Append("<td>" + item.SpreadsheetLineNumbers + "</td>");
}
// 'item' is either DuplicateSpreadsheetRowModel class or SpreadsheetRowModel class
With the above code I get the following error:
No, it's not possible. Generic types must be known at compile time.Think about it for a minute, how could compiler know that it is guaranteed that the type T
has SpreadsheetLineNumbers
property? What if T
is primitive type such as int
or object
?
What prevents us from calling method with ref _, 999
parameters (T is int here) ?
It'd only work if we add an interface that contains this property :
public interface MyInterface
{
string SpreadsheetLineNumbers { get; set; }
}
And let your class inherit from this interface
public class MyClass : MyInterface
{
public string SpreadsheetLineNumbers { get; set; }
}
Then we could use generic type constraints to let compiler know that the type T derives from this interface and therefore it has to contain and implement all its members:
private void GetGenericTableContent<T>(ref StringBuilder outputTableContent, T item)
where T : IMyInterface // now compiler knows that T type has implemented all members of the interface
{
outputTableContent.Append("<td>" + item.SpreadsheetLineNumbers + "</td>");
}
这篇关于'T'不包含定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!