Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

c# - 'T' does not contain a definition

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:

'T' does not contain a definition for 'SpreadsheetLineNumbers' and no extension method 'SpreadsheetLineNumbers' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...