Tag: generics

C# – 静态类型不能用作类型参数

我有一个generics类,可以帮助我对参数值进行检查 internal sealed class Argument where T : class { private void TraceAndThrow(Exception ex) { new InternalTraceHelper().WriteError(ex); throw ex; } internal void ThrowNull(object value, string argName) { if (ReferenceEquals(value, null)) { TraceAndThrow(new ArgumentNullException(argName)); } } internal void ThrowIf(bool condition, string argName) { if (condition) { TraceAndThrow(new ArgumentException(null, argName)); } } internal void ThrowNotInEnum(Type enumType, object […]

C#:强制转换为基类型的通用接口

这是代码: public interface IValidator { bool IsValid(T obj); } public class OrderValidator: IValidator { // … } public class BaseEntity { } public class Order: BaseEntity { } 问题是我做不到: var validator = new OrderValidator(); // this line throws because type can’t be converted var baseValidator = (IValidator)validator; // all this is because I need a […]

C#LINQ to SQL:重构此通用GetByID方法

我写了以下方法。 public T GetByID(int id) { var dbcontext = DB; var table = dbcontext.GetTable(); return table.ToList().SingleOrDefault(e => Convert.ToInt16(e.GetType().GetProperties().First().GetValue(e, null)) == id); } 基本上它是Generic类中的一个方法,其中T是DataContext中的一个类。 该方法从T( GetTable )的类型获取表,并检查输入参数的第一个属性(始终是ID)。 这个问题是我必须首先将元素表转换为列表以在属性上执行GetType ,但这不是很方便,因为必须枚举表的所有元素并将其转换为List 。 如何重构此方法以避免整个表上的ToList ? [更新] 我无法直接在表上执行Where的原因是因为我收到此exception: 方法’System.Reflection.PropertyInfo [] GetProperties()’没有支持的SQL转换。 因为GetProperties无法转换为SQL。 [更新] 有人建议使用T的接口,但问题是T参数将是[DataContextName] .designer.cs中自动生成的类,因此我无法使其实现接口(并且它不可行实现LINQ的所有这些“数据库类”的接口;并且,一旦我将新表添加到DataContext,该文件将被重新生成,从而丢失所有写入的数据)。 所以,必须有一个更好的方法来做到这一点…… [更新] 我现在已经按照Neil Williams的建议实现了我的代码,但我仍然遇到问题。 以下是代码的摘录: 接口: public interface IHasID { int ID { get; set; […]

为什么C#(4.0)不允许generics类型中的共同和逆变?

这种限制的真正原因是什么? 这只是必须完成的工作吗? 概念上难吗? 这不可能吗? 当然,人们不能在字段中使用类型参数,因为它们总是可读写的。 但这不是答案,可以吗? 这个问题的原因是我在C#4上写了一篇关于方差支持的文章,我觉得我应该解释为什么它仅限于委托和接口。 只是为了逆转举证责任。 更新:埃里克问了一个例子。 怎么样(不知道这是否有意义,但是:-)) public class Lookup where T : Animal { public T Find(string name) { Animal a = _cache.FindAnimalByName(name); return a as T; } } var findReptiles = new Lookup(); Lookup findAnimals = findReptiles; 在一个类中拥有它的原因可能是类本身中保存的缓存。 请不要将您的不同类型的宠物命名为相同! 顺便说一下,这让我想到了C#5.0中的可选类型参数 🙂 更新2:我没有声称CLR和C#应该允许这个。 只是想了解是什么导致它没有。

为什么我不能将List 分配给List ?

我定义了以下类: public abstract class AbstractPackageCall { … } 我还定义了这个类的子类: class PackageCall : AbstractPackageCall { … } AbstractPackageCall还有其他几个子节点 现在我想进行以下调用: List calls = package.getCalls(); 但我总是得到这个例外: Error 13 Cannot implicitly convert type ‘System.Collections.Generic.List’ to ‘System.Collections.Generic.List’ 这里有什么问题? 这是Package#getCalls的方法 internal List getCalls() { return calls; }

对约束generics类型参数的inheritance

我知道不可能从generics类型参数inheritance,但是当为抽象类型的衍生物实现公共代理时它会很方便:-) 有谁知道为什么这是不可能的? 示例C#: abstract class Foo { public virtual void Bar() { // nop } } class FooProxy : TFoo where TFoo : Foo { public override void Bar() { // do some stuff before base.Bar(); // do some stuff after } } 编辑:一些代码来说明如何使用它的示例。 考虑Foo的以下衍生物: class FooX : Foo { public string X { get; […]

在运行时指定generics集合类型参数

我有: class Car {..} class Other{ List GetAll(){..} } 我想要做: Type t = typeof(Car); List Cars = GetAll(); 我怎样才能做到这一点? 我想从我在运行时使用reflection发现的类型的数据库中返回一个generics集合。

在不使用GetMethods的情况下获取通用方法

我想得到方法System.Linq.Queryable.OrderyBy(the IQueryable source, Expression<Func> keySelector)方法,但我一直提出空值。 var type = typeof(T); var propertyInfo = type.GetProperty(group.PropertyName); var propertyType = propertyInfo.PropertyType; var sorterType = typeof(Func).MakeGenericType(type, propertyType); var expressionType = typeof(Expression).MakeGenericType(sorterType); var queryType = typeof(IQueryable); var orderBy = typeof(System.Linq.Queryable).GetMethod(“OrderBy”, new[] { queryType, expressionType }); /// is always null. 有没有人有任何见解? 我宁愿不循环GetMethods结果。

没有使用generics扩展方法的类型推断

我有以下方法: public static TEventInvocatorParameters Until (this TEventInvocatorParameters p, Func breakCond) where TEventInvocatorParameters : EventInvocatorParameters where TEventArgs : EventArgs { p.BreakCondition = breakCond; return p; } 而这堂课 public class EventInvocatorParameters where T : EventArgs { public Func BreakCondition { get; set; } // Other properties used below omitted for brevity. } 现在,我有以下问题: 此扩展方法显示所有类型,甚至是string 。 我不能写new EventInvocatorParameters(EventABC).Until(e […]

在运行时设置generics类型

我上课了 public class A { public static string B(T obj) { return TransformThisObjectToAString(obj); } } 上面使用字符串纯粹是示范性的。 我可以在已知/指定的类型上调用这样的静态函数: string s= A.B(objectOfKnownType); 如果我事先不知道T ,我该怎么做这个调用,而是我有一个Type类型的变量来保存类型。 如果我这样做: Type t= typeof(string); string s= A.B(someStringObject); 我得到这个编译器错误: Cannot implicitly convert type ‘t’ to ‘object’