简体   繁体   English

具有包含/任何功能的类型和实例的集合

[英]Collection of Types and Instances with Contains/Any Functionality

How can I create a collection of types and instances with Contains/ContainsKey/Any functionality?如何创建具有包含/包含键/任何功能的类型和实例的集合? I've tried using dictionaries, valuetuple lists, and looked into other options, but am consistently stymied by is a type, which is not valid in the given context errors.我尝试过使用字典、值元组列表,并研究其他选项,但我一直受阻于is a type, which is not valid in the given context错误中is a type, which is not valid in the given context

For example, here is my List + LINQ attempt with this error:例如,这是我的 List + LINQ 尝试并出现此错误:

var activeReports = new List<(Type Type, IReport Instance)>();

if (activeReports.Any(x => x.Type == Reports.Daily))
{

};

and here is my dictionary attempt:这是我的字典尝试:

var activeReports = new Dictionary<Type, IReport>();

if (activeReports.ContainsKey(Reports.Daily))
{

};

In both attempts, the is a type, which is not valid in the given context error occurs on Reports.Daily .在这两次尝试中, is a type, which is not valid in the given contextReports.Daily发生is a type, which is not valid in the given context

Context: I'm trying to create a collection of active reports from a large group of possibilities.上下文:我正在尝试从一大组可能性中创建活动报告的集合。

The nomenclature starts to eat its own tail here, which is confusing.命名法在这里开始吃自己的尾巴,这是令人困惑的。 What you need to do is make sure you're sending the methods a Type object , as opposed to the actual type .您需要做的是确保向方法发送一个Type对象,而不是实际的type A Type object describes a type—and includes a ton of useful metadata about it. Type对象描述了一种类型——并包含大量关于它的有用元数据。

You can get a Type object by using the built-in typeof() operator on the type (eg, typeof(Reports.Daily) ):您可以通过在Type使用内置的typeof()运算符来获取Type对象(例如, typeof(Reports.Daily) ):

var activeReports = new Dictionary<Type, IReport>();

if (activeReports.ContainsKey(typeof(Reports.Daily))) { … }

Alternatively, if you already have an existing instance of a type, you can get its Type object dynamically at runtime by using the .GetType() method on the existing object instance:或者,如果您已经有一个类型的现有实例,您可以在运行时通过在现有对象实例上使用.GetType()方法动态获取其Type对象:

var dailyReport = new Reports.Daily();
var activeReports = new Dictionary<Type, IReport>();

if (activeReports.ContainsKey(dailyReport.GetType())) { … }

Note: GetType() is defined on the base Object class and, thus, available to all objects in C#, regardless of their type.注意: GetType()是在基础Object类上定义的,因此可用于 C# 中的所有对象,无论它们的类型如何。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM