我有以下(简化的)方法:privatestaticstringGetStringFromValue(Tval){if(typeof(T)==typeof(DateTime)){returnstring.Format("{0}",((DateTime)val).Year.ToString("0000"));}returnstring.Empty;}在强制转换“(DateTime)val”时出现以下错误:CannotcastexpressionofType'T'totype'DateTime'如何访问DateTime参数的Year属性?更新:感谢您所有快速的答复。这个方法(和方法名称)真的
我想知道如何通过Func至Func方法参数:publicvoidFoo(Funcp)whereT:class{Foo(p);}publicvoidFoo(Funcp){}奇怪的是,它在NET4.0类库中有效,但在Silverlight4类库中无效。实际上我希望它在Silverlight中工作,并且我有像Func这样的输入参数 最佳答案 这样就可以了:publicvoidFoo(Funcp)whereT:class{Funcf=()=>p();Foo(f);} 关于c#-将Func转换为F
我想要一个可以执行任何外部方法的类,如下所示:classCrazyClass{//otherstuffpublicAnyReturnTypeExecute(AnyKindOfMethodMethod,object[]ParametersForMethod){//morestuffreturnMethod(ParametersForMethod)//orsomethinglikethat}}这可能吗?是否有采用任何方法签名的委托(delegate)? 最佳答案 您可以通过Func以不同的方式执行此操作和关闭:publicTExecut
如果我有一个数组。我可以从该数组填充通用列表吗:Foo[]fooList...(assumepopulatedarray)//Thisdoesn'tseemtoworkListnewList=newList(fooList); 最佳答案 您可以将数组转换为列表:string[]strings={"hello","world"};IListstringList=strings.ToList(); 关于c#-从数组填充列表,我们在StackOverflow上找到一个类似的问题:
如何在wcf服务中使用泛型方法?我写了这段代码:[OperationContract]voidAddItem(Titem);但我收到以下错误:Type'T'cannotbeexportedasaschematypebecauseitisanopengenerictype.Youcanonlyexportagenerictypeifallitsgenericparametertypesareactualtypes. 最佳答案 你根本做不到。这是不可能的,因为soap不支持这个。看这个article,其中提到如何绕过泛型,方法是创建一个
我有下面的代码,我需要将一个字符串转换为同样从String指定的类型:Typet=Type.GetType("System.Nullable`1[[System.DateTime,mscorlib,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089]]");objectd=Convert.ChangeType("2012-02-2310:00:00",t);我收到以下错误消息:Invalidcastfrom'System.String'to'System.Nullable`1[[System.DateTime,
我有一个ICollection类型的对象.转换为string[]的最佳方式是什么?.如何在.NET2中完成此操作?如何在更高版本的C#中更清晰地完成此操作,或许在C#3中使用LINQ? 最佳答案 您可以使用以下代码片段将其转换为普通数组:string[]array=newstring[collection.Count];collection.CopyTo(array,0);这应该可以完成工作:) 关于c#-ICollection到string[],我们在StackOverflow上找到一
这个问题在这里已经有了答案:Convertingastringtoaclassname(2个答案)关闭9年前。我有一个像这样的通用类:publicclassRepository{...}我需要用一个字符串来实例化它...示例:string_sample="TypeRepository";var_rep=newRepository();我该怎么做?这可能吗?谢谢!
我有一个像这样的枚举类型作为例子:publicEnumMyEnum{enum1,enum2,enum3};我将从配置文件中读取一个字符串。我需要的是将字符串解析为MyEnum类型或null或未定义。不确定以下代码是否有效(很抱歉现在无法访问我的VS)://example:ParseEnum("ENUM1",refeVal);boolParseEnum(stringvalue1,refeVal)whereT:Enum{boolbRet=false;varx=fromxinEnum.GetNames(typeof(T))wherestring.Equals(value1,x,StringC
好吧,我是一个开始使用C#的Java人,我正在编写代码并开始制作一个泛型方法,我编写的内容可以运行和编译,但它违背了我所知道的关于泛型应该如何工作的一切,所以我希望有人可以向我解释一下:所以我有一个泛型方法定义如下:publicstaticListCopyAsList(IEnumerablelist,ObjectlockObject){if(list!=null){lock(lockObject){returnnewList(list);}}returnnull;}但对我来说奇怪的是,我可以在不指定T的情况下调用这个通用方法,它会起作用:Liststrings=newList(){"a