Tag: 铸造

通用Type参数没有装箱或类型参数转换

我有以下帮助方法: public static T CreateRequest() where T : Request, new() { T request = new T(); // … // Assign default values, etc. // … return request; } 我想从另一个帮助器中的另一个方法内部使用此方法: public T Map(F value, T toValue) where T : new() where F : new() { if (typeof(T).BaseType.FullName == “MyNamespace.Request”) { toValue = MyExtensions.CreateRequest(); } else { […]

在C#.NET中即时转换为Type

我想将Object转换为将在运行时分配的类型。 例如,假设我有一个函数将字符串值(从TextBox or Dropdownlist )分配给Object.Property 。 如何将值转换为正确的类型? 例如,它可以是整数,字符串或枚举。 Public void Foo(object obj,string propertyName,object value) { //Getting type of the property og object. Type t= obj.GetType().GetProperty(propName).PropertyType; //Now Setting the property to the value . //But it raise an error,because sometimes type is int and value is “2” //or type is enum (ea: Gender.Male) and value is […]

C#性能分析 – 如何计算CPU周期?

这是进行性能分析的有效方法吗? 我希望获得纳秒精度并确定类型转换的性能: class PerformanceTest { static double last = 0.0; static List numericGenericData = new List(); static List numericTypedData = new List(); static void Main(string[] args) { double totalWithCasting = 0.0; double totalWithoutCasting = 0.0; for (double d = 0.0; d < 1000000.0; ++d) { numericGenericData.Add(d); numericTypedData.Add(d); } Stopwatch stopwatch = new Stopwatch(); for (int […]

为什么Dictionary <T1,List >不能转换为Dictionary <T1,IEnumerable >?

我想知道为什么我不能只是演员(我有一个模糊的想法,这可能与那个共同/逆转的东西有关?),我被迫将第一个字典的元素复制到新的字典中得到我想要的类型?

使用动态generics类型参数创建generics类的实例

我需要像这样创建一个generics类的实例: Type T = Type.GetType(className).GetMethod(functionName).ReturnType; var comparer = new MyComparer(); // ERROR: “The type or namespace name ‘T’ could not be found” 我发现这个答案只有通过反思才能实现。 但是使用reflection我得到了我需要转换为我的generics类型的对象。 我试过这样的 Type myGeneric = typeof(MyComparer); Type constructedClass = myGeneric.MakeGenericType(); object created = Activator.CreateInstance(constructedClass); var comparer = (T)Convert.ChangeType(created, T);// ERROR: “The type or namespace name ‘T’ could not be found” 但得到同样的错误。 怎么解决? […]

如何使用类型名称作为字符串转换为类型?

好吧,我现在整天都在喋喋不休地谈论这个想法,而且我已经达到了我承认我只是不知道的部分。 我正在做的事情可能只是愚蠢而且有更好的方法,但这是我思考带给我的地方。 我试图使用通用方法在WinForms中加载表单: protected void LoadForm(ref T formToShow, bool autoLoaded) where T : FormWithWorker, new() { // Do some stuff } 表单由ToolStripMenuItem加载(通过选择项目或使用“打开Windows”菜单项)。 它们是延迟加载的,因此MDI父级中的表单有字段,但在需要它们之前它们为空。 我有一个用于处理所有菜单项单击的ToolStripMenuItem_Click的常用方法。 除了ToolStripMenuItem的名称与为其对应的表单类名称选择的模式匹配之外,该方法没有真正的方法来知道调用哪个表单。 因此,使用ToolStripMenuItem的名称,我可以为所请求的表单类型的名称和分配用于存储该表单的引用的私有字段的名称。 使用它,我可以使用具有硬编码类型的增长/收缩switch语句和字符串匹配来调用具有特定类型集(不需要的)的方法,或者我可以使用Reflection来获取字段并创建该类型的实例。 我遇到的问题是, System.Activator.CreateInstance提供了一个无法转换为我需要的类型的ObjectHandler。 这是我到目前为止的一小部分: string formName = “_form” + ((ToolStripMenuItem)sender).Name.Replace(“ToolStripMenuItem”, “”); string formType = formName.Substring(1); FieldInfo fi = this.GetType().GetField(formName, BindingFlags.NonPublic | BindingFlags.Instance); FormWithWorker formToLoad = (FormWithWorker)fi.GetValue(this); if (formToLoad == […]

如何将类型为string的对象动态转换为类型为T的对象

我有这个XML文档 False 在我的代码中,我正在尝试构建一个包含节点的参数数组。 object test = (object) ((typeof(publishNode.Attributes[“Type”].value)) publishNode.InnerText); 这当然在编译时打破了。 我无法弄清楚如何将publishNode.InnerText(‘false’)转换为XML文件中指定类型的运行时定义对象,并将其存储在对象中(这将保留类型)。

如何在不知道封闭generics类型的情况下访问通用属性

我有一个通用类型如下 public class TestGeneric { public T Data { get; set; } public TestGeneric(T data) { this.Data = data; } } 如果我现在有一个对象(来自某个外部源),我知道它的类型是一些封闭的TestGeneric ,但我不知道TypeParameter T.现在我需要访问我的对象的数据。 问题是我无法转换对象,因为我不确切知道哪个封闭的TestGeneric。 我用 // thx to http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class private static bool IsSubclassOfRawGeneric(Type rawGeneric, Type subclass) { while (subclass != typeof(object)) { var cur = subclass.IsGenericType ? subclass.GetGenericTypeDefinition() : subclass; if (rawGeneric == cur) […]

C# – 装箱/拆箱/类型转换的问题。 我不明白

我很难理解这一点。 请考虑以下示例: protected void Page_Load(object sender, EventArgs e) { // No surprise that this works Int16 firstTest = Convert.ToInt16(0); int firstTest2 = (int)firstTest; // This also works object secondTest = 0; int secondTest2 = (int)secondTest; // But this fails! object thirdTest = Convert.ToInt16(0); int thirdtest2 = (int)thirdTest; // It blows up on this line. } […]

c#在运行时创建未知的generics类型

所以我有一个generics的类,它可能需要在它的方法中自己创建一个自己的实例,使用不同类型的generics,这种类型是通过relfection获得的。 这很重要,因为这个Repository将T映射到数据库表[这是我正在编写的ORMish],如果代表T的类有一个代表另一个表的集合,我需要能够实例化并将其传递给存储库[ala Inception ]。 我提供的方法是为了让它更容易看到问题。 private PropertiesAttributesAndRelatedClasses GetPropertyAndAttributesCollection() { // Returns a List of PropertyAndAttributes var type = typeof(T); //For type T return an array of PropertyInfo PropertiesAttributesAndRelatedClasses PAA = new PropertiesAttributesAndRelatedClasses(); //Get our container ready PropertyAndAttributes _paa; foreach (PropertyInfo Property in type.GetProperties()) //Let’s loop through all the properties. { _paa = new PropertyAndAttributes(); //Create […]