我有这门课:class Foo { public string Name { get; set; }
}而这堂课class Foo<T> : Foo {public T Data { get; set; }
}这就是我想要做的事情:public Foo<T> GetSome() {Foo foo = GetFoo();Foo<T> foot = (Foo<T>)foo;foot.Data = GetData<T>();return foot;
}将Foo转换为Foo< T>?的最简单方法是什么?我无法直接转换InvalidCastException)并且我不想手动复制每个属性(在我的实际用例中,有多个属性),如果我不需要.是用户定义...
参见英文答案 > Why does a generic type constraint result in a no implicit reference conversion error? 5个我正在尝试从接口继承两个不同的模型.这些模型应该作为List或Collection传递给Method.现在我收到此错误消息:The type 'InheritanceTest.FooModel' cannot be used as type parameter 'T' in the generic type or method 'InheritanceTest.Service.DoSomethingWith<T>(System.Coll...
是否有可能得到一个反射获得的类型的“c#名称”,如:System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]我想得到:List<String>没有拆分字符串有可能吗?例如,使用Reflection.
谢谢!解决方法:是的,你可以通过使用CodeDom和CSharpCodeProvider来分割,解析或操??纵字符串来实现它:using CodeDom;
using Microsoft.CSharp;// ...Type yourType = t...
在.NET中,我有一个ConstructorInfo实例.声明类型是构造的泛型类型(aka foo.DeclaringType.IsConstructedGenericType == true).我想检索属于开放类型的ConstructorInfo实例-即声明类型的通用类型定义.
使用foo.DeclaringType.GetGenericTypeDefinition();可以直接获取开放类型.但是,目前还没有明显的方法来获取匹配的构造函数.我可以重新枚举双方的所有构造函数,但是,我仍然面临着将这两个列表匹配在一起的问题.而且我不确定.NET是否...
前言
泛型:通过参数化类型来实现在同一份代码上操作多种数据类型。利用“参数化类型”将类型抽象化,从而实现灵活的复用。在.NET类库中处处都可以看到泛型的身影,尤其是数组和集合中,泛型的存在也大大提高了程序员的开发效率。更重要的是,C#的泛型比C++的模板使用更加安全,并且通过避免装箱和拆箱操作来达到性能提升的目的。因此,我们很有必要掌握并善用这个强大的语言特性。
C#泛型特点:
1、如果实例化泛型类型的参数相同,...
我有一个通用类型Foo1,它基本上是一个带有一些元数据和通用列表的容器.当我序列化该类型时,它将获得名称“ Foo1Of” TypeParameterName.public class Foo1<T>
{public string Name { get; set; } = string.Empty;public List<T> List { get; set; } = new List<T>();
}[TestMethod]
public void SerializeFoo1()
{Foo1<string> foo = new Foo1<string>{Name = "Foo1",List ={"Bar","Baz"}};XmlSerializer s = new XmlSerializer(fo...
public interface ICardEntity { ... }public class Card : ICardEntity { ... }public static class MyExtensions
{public static List<T> ToList<T>(this IQueryable<T> query) where T : ICardEntity{ ... }
}// DbContext
public class ApplicationDbContext : DbContext
{public DbSet<Card> Cards { get; set; }
}.....var list = dbContext.Cards.ToList(); // -- OK, my extension is called
var list2 = dbContext.Cards....
我经常忘记在定义协变和逆变泛型类型时是否必须使用in或out.在Java中,我有助记符PECS(生产者扩展了超级用户)来帮助我.您知道c#的类似助记符吗?解决方法:当他们称呼它们为“内”和“外”而不是协变和逆变时,他们不是为我们这样做吗?试想一下:我是在“推高”价值观还是在“推高”价值观?如果不确定,请尝试“退出”-它更常见(更容易理解).
C#中有没有一种方法可以对泛型类型执行用户定义的转换?
例如:class Stack<T>
{private T x; //should be an array but doesn't matter for this examplepublic Stack(T input){x = input;}public Stack<Q> Convert<Q>(Stack<T> inputStack){//what would go here ? The call is below.}
}//main code
Stack<int> stack = new Stack<int>(2);
Stack<long> longstack = stack.Convert<long>(stack);我可以想象编译器可以在Convert...
一点代码:public interface IMyInterface
{int GetIt();
}public class MyImplementation : IMyInterface
{public int GetIt(){return 10;}
}[Test]public void Testit(){Method<MyImplementation>();}private void Method<T>()where T : class , IMyInterface{var mock = new Mock<T>();mock.Setup(m => m.GetIt()).Returns(() =>{return 40;});Assert.AreEqual(40, mock.Object.GetIt());}请注意,在新建Mock时我使用的是泛型T,但...
在Java中,我可以使用Generic Type中的extend关键字来做到这一点,但是在C#中,我无法弄清楚.
我有3个班级,其中一个是基班.public class BaseEntity { public string Id {get;set;}
}public class EntityA : BaseEntity {}public class EntityB: BaseEntity {}然后我有一个用于数据集的模拟类.对于泛型类型,最小约束是BaseEntitypublic class MockDataStore<T> : IDataStore<T> where T : BaseEntity
{List<T> items = new List<T>()...
我有以下实用程序例程,用于确定类型是否从特定类型派生:private static bool DerivesFrom(Type rType, Type rDerivedType)
{while ((rType != null) && ((rType != rDerivedType)))rType = rType.BaseType;return (rType == rDerivedType);
}(实际上,我不知道是否有更方便的方法来测试派生…)
问题是我想确定一个类型是否派生自一个泛型类型,但是没有指定泛型参数.
例如,我可以写:DerivesFrom(typeof(ClassA), typeof(MyGenericC...
我有两个通用类:public class First<T>
{...
}
public class Second<T>
{...
}我使用Second类作为First类构造函数的参数:var instance = new First<int>(new Second<int>());是否可以仅为First类构造函数指定泛型类型(在我的示例中为整数),如下所示:var instance = new First<int>(new Second());?解决方法:我相信通用构造函数参数的类型推断正被添加到C#6中.现在,答案是否定的.
是否可以创建一个类型必须具有索引器的泛型类/方法?
我的想法是让以下两种扩展方法适用于使用索引器获取和设置值的任何类型,但似乎无法找到任何关于它的内容.只有关于使索引器本身通用的东西,这不是我追求的……public static T GetOrNew<T>(this HttpSessionStateBase session, string key) where T : new(){var value = (T) session[key];return ReferenceEquals(value, null) ? session.Set(key, new T()) : value;}public sta...
我有琐碎的通用枚举解析方法:public static T Parse<T>(string value) => (T)Parse(typeof(T), value, false);用法是:public IEnumerable<DocumentTypesEnum> FileTypeEnums => FileTypes.Split(',').Select(Extensions.StringEnumerator.Parse<DocumentTypesEnum>);以上编译很好.
将可选参数添加到Parse< T>:public static T Parse<T>(string value, bool ignoreCase = false) => (T)Parse(typeof(T), value, ignoreCase);现在...