No. Generic types must be known at compile time.
Think about it for a minute, how could compiler know that it is guaranteed that type T
has property SpreadsheetLineNumbers
? What if T
is of primitive type such as int
or object
?
What prevents us from calling the method like this: GetGenericTableContent(ref _, 999)
with T as int here ?
To fix it you could first add an interface that contains the 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 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 type T has implemented SpreadsheetLineNumbers
{
outputTableContent.Append("<td>" + item.SpreadsheetLineNumbers + "</td>");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…