Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 泛型,其中按类字段的限制_C#_Generics_Inheritance - Fatal编程技术网

C# 泛型,其中按类字段的限制

C# 泛型,其中按类字段的限制,c#,generics,inheritance,C#,Generics,Inheritance,是否可以在C中使用where来创建泛型限制,以仅选择具有某些名称的字段的类 例如,我有AbstractService 我有一个方法IEnumerable ProvideDatauserId 在提供数据的内部,我应该只选择具有相同用户bla-bla-bla.Whered=>d.UserId==UserId的实例。但无法解析d.UserId。如何解决这个问题 重要提示:我无法从类或接口继承t,因为类或接口具有UserID字段。接口就是您要查找的: public interface IWithSome

是否可以在C中使用where来创建泛型限制,以仅选择具有某些名称的字段的类

例如,我有AbstractService 我有一个方法IEnumerable ProvideDatauserId

在提供数据的内部,我应该只选择具有相同用户bla-bla-bla.Whered=>d.UserId==UserId的实例。但无法解析d.UserId。如何解决这个问题


重要提示:我无法从类或接口继承t,因为类或接口具有UserID字段。

接口就是您要查找的:

public interface IWithSomeField
{
     int UserId { get; set; }
}

public class SomeGenericClasss<T> 
  : where T : IWithSomeField
{

}

public class ClassA : IWithSomeField // Can be used in SomeGenericClass
{
     int UserId { get; set; }
}

public class ClassB  // Can't be used in SomeGenericClass
{

}
您可以使用自己的代码包装它们:

public interface IWithUserId
{
    public int UserId { get; set; }
}
public partial class ClassA : IWithUserId 
{

}
public partial class ClassB  : IWithUserId
{

}
然后,对于您的服务,您可以为几个web服务中的任何一个类实例化AbstractService:

public class AbstractService<T> where T : IWithUserId
{
}

此技术非常有效,但仅当您可以在同一项目中扩展类时才适用,因为使用了部分关键字技巧。

您需要的是一个接口:

public interface IWithSomeField
{
     int UserId { get; set; }
}

public class SomeGenericClasss<T> 
  : where T : IWithSomeField
{

}

public class ClassA : IWithSomeField // Can be used in SomeGenericClass
{
     int UserId { get; set; }
}

public class ClassB  // Can't be used in SomeGenericClass
{

}
您可以使用自己的代码包装它们:

public interface IWithUserId
{
    public int UserId { get; set; }
}
public partial class ClassA : IWithUserId 
{

}
public partial class ClassB  : IWithUserId
{

}
然后,对于您的服务,您可以为几个web服务中的任何一个类实例化AbstractService:

public class AbstractService<T> where T : IWithUserId
{
}

此技术非常有效,但仅当您可以在同一项目中扩展类时才适用,因为使用了部分关键字技巧。

您更新了问题,告知无法继承接口。。。让我尝试另一种想法当从另一个类继承时,或者不允许实现接口时,那么恐怕不可能。您更新了问题,告诉我继承接口是不可能的。。。让我尝试另一种想法,当从另一个类继承时,或者不允许实现接口时,那么恐怕不可能。