'T' does not contain a definition

前端 未结 3 1224
灰色年华
灰色年华 2020-12-17 17:28

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,

3条回答
  •  Happy的楠姐
    2020-12-17 18:08

    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(ref StringBuilder outputTableContent, T item) 
        where T : IMyInterface // now compiler knows that T type has implemented all members of the interface
    {
        outputTableContent.Append("" + item.SpreadsheetLineNumbers + "");
    }
    

提交回复
热议问题