简体   繁体   中英

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.

For example, here is my List + LINQ attempt with this error:

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 .

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 . A Type object describes a type—and includes a ton of useful metadata about it.

You can get a Type object by using the built-in typeof() operator on the type (eg, 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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