T does not contain a definition for RowKey

I am trying to create a generic class:

public class ClassName<T>
{
    public T AccessEntity(string id)
    {
        return (from e in ServiceContext.CreateQuery<T>(TableName)
                where e.RowKey == id // error here!
                select e).FirstOrDefault();
    }
}

There is an error in this code:

T does not contain a definition for RowKey

but the parameters that will replace T at runtime have a RowKey definition. Perhaps because complier does not get the definition of RowKey in T at compile time, so I get this error. Can someone tell me how to solve this problem?

+5
source share
5 answers

To do this, you will need an interface restriction:

interface IHazRowKey {
     string RowKey { get; } 
}

And indicate this restriction:

public class classname<T> where T : IHazRowKey {...}

And indicate : IHazRowKeyfor each of the implementations:

public class Foo : IHazRowKey {....}

RowKey ( , ), . ( , IMO), :

public class Foo : IHazRowKey {
    string HazRowKey.RowKey { get { return this.RowKey; } }
    ...
}
+11

++ #: , generic, T , . , # (, # ).

T, . RowKey where T : myinterface .

+8

, :

public interface IHasRowKey
{
   string RowKey {get;}
}

public class classname<T> where T : IHasRowKey
{

}
+3
class YourClass // or extract an interface
{
    public string RowKey { get; set; }
}

class YourGeneric<T> where T : YourClass
{
    // now T is strongly-typed class containing the property requested
}
+1

RowKey, , . , . Generic. :.

public class ClassName<T> {
    private T _genericType;
    public ClassName(T t) {
        _genericType = t;
    }

    public void UseGenericType() {
        // Code below allows you to get RowKey property from your generic 
        // class type param T, cause you can't directly call _genericType.RowKey
        PropertyInfo rowKeyProp = _genericType.GetType().GetProperty("RowKey");
        if(rowKeyProp != null) { // if T has RowKey property, my case different T has different properties and methods
            string rowKey = rowKeyProp.GetValue(_genericType).ToString();
            // Set RowKey property to new value
            rowKeyProp.setValue(_genericType, "new row key");
        }
    }
}

Here is a link to the PropertyInfo class http://msdn.microsoft.com/en-us/library/System.Reflection.PropertyInfo_methods(v=vs.110).aspx

0
source

All Articles