How to check a generic type in C++/CLI? - c++-cli

In C++/CLI code I need to check if the type is a specific generic type. In C# it would be:
public static class type_helper {
public static bool is_dict( Type t ) {
return t.IsGenericType
&& t.GetGenericTypeDefinition() == typeof(IDictionary<,>);
}
}
but in cpp++\cli it does not work the same way, compiler shows the syntax error:
class type_helper {
public:
static bool is_dict( Type^ t ) {
return t->IsGenericType && t->GetGenericTypeDefinition()
== System::Collections::Generic::IDictionary<,>::typeid;
}
};
The best way I find is compare strings like this:
class type_helper {
public:
static bool is_dict( Type^ t ) {
return t->IsGenericType
&& t->GetGenericTypeDefinition()->Name == "IDictionary`2";
}
};
Does anybody know the better way?
PS:
Is it limitation of typeof (typeid) in c++\cli or I do not know "correct" systax?

You could write:
return t->IsGenericType
&& t->GetGenericTypeDefinition() == System::Collections::Generic::IDictionary<int,int>::typeid->GetGenericTypeDefinition();

Related

Check If Object Is List(Of Anything) [duplicate]

public bool IsList(object value)
{
Type type = value.GetType();
// Check if type is a generic list of any type
}
What's the best way to check if the given object is a list, or can be cast to a list?
For you guys that enjoy the use of extension methods:
public static bool IsGenericList(this object o)
{
var oType = o.GetType();
return (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(List<>)));
}
So, we could do:
if(o.IsGenericList())
{
//...
}
using System.Collections;
if(value is IList && value.GetType().IsGenericType) {
}
bool isList = o.GetType().IsGenericType
&& o.GetType().GetGenericTypeDefinition() == typeof(IList<>));
public bool IsList(object value) {
return value is IList
|| IsGenericList(value);
}
public bool IsGenericList(object value) {
var type = value.GetType();
return type.IsGenericType
&& typeof(List<>) == type.GetGenericTypeDefinition();
}
Here's an implementation that works in .NET Standard, and works against interfaces:
public static bool ImplementsGenericInterface(this Type type, Type interfaceType)
{
return type
.GetTypeInfo()
.ImplementedInterfaces
.Any(x => x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == interfaceType);
}
And here are the tests (xunit):
[Fact]
public void ImplementsGenericInterface_List_IsValidInterfaceTypes()
{
var list = new List<string>();
Assert.True(list.GetType().ImplementsGenericInterface(typeof(IList<>)));
Assert.True(list.GetType().ImplementsGenericInterface(typeof(IEnumerable<>)));
Assert.True(list.GetType().ImplementsGenericInterface(typeof(IReadOnlyList<>)));
}
[Fact]
public void ImplementsGenericInterface_List_IsNotInvalidInterfaceTypes()
{
var list = new List<string>();
Assert.False(list.GetType().ImplementsGenericInterface(typeof(string)));
Assert.False(list.GetType().ImplementsGenericInterface(typeof(IDictionary<,>)));
Assert.False(list.GetType().ImplementsGenericInterface(typeof(IComparable<>)));
Assert.False(list.GetType().ImplementsGenericInterface(typeof(DateTime)));
}
if(value is IList && value.GetType().GetGenericArguments().Length > 0)
{
}
Based on Victor Rodrigues' answer, we can devise another method for generics. In fact, the original solution can be reduced to only two lines:
public static bool IsGenericList(this object Value)
{
var t = Value.GetType();
return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>);
}
public static bool IsGenericList<T>(this object Value)
{
var t = Value.GetType();
return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<T>);
}
I'm using the following code:
public bool IsList(Type type) => type.IsGenericType && (
(type.GetGenericTypeDefinition() == typeof(List<>))
|| (type.GetGenericTypeDefinition() == typeof(IList<>))
);
Probably the best way would be to do something like this:
IList list = value as IList;
if (list != null)
{
// use list in here
}
This will give you maximum flexibility and also allow you to work with many different types that implement the IList interface.

ArrayList partial integrating one List in another

I have a function that creates regular Objects of a same type and I cannot avoid that step.
When I use List.addAll(*) I will get many "Duplications" that are not equal in sense of Objectivity.
I have a very bad coded solution and want to ask if there could be a better or more effective one maybe with Java-Util-functions and defining a Comparator for that single intermezzo?
Here is my bad smell:
private void addPartial(List<SeMo_WikiArticle> allnewWiki, List<SeMo_WikiArticle> newWiki) {
if(allnewWiki.isEmpty())
allnewWiki.addAll(newWiki);
else{
for(SeMo_WikiArticle nn : newWiki){
boolean allreadyIn = false;
for(SeMo_WikiArticle oo : allnewWiki){
if(nn.getID()==oo.getID())
allreadyIn= true;
}
if(!allreadyIn)
allnewWiki.add(nn);
}
}
}
Any Ideas?
Add an override function of equals() into class SeMo_WikiArticle :
class SeMo_WikiArticle {
// assuming this class has two properties below
int id;
String name;
SeMo_WikiArticle(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public boolean equals(Object obj) {
// implement your own comparison policy
// here is an example
if (obj instanceof SeMo_WikiArticle) {
SeMo_WikiArticle sw = (SeMo_WikiArticle)obj;
if (this.id == sw.id && (this.name == sw.name || this.name.equals(sw.name))) {
return true;
}
}
return false;
}
}
After that you can use contains() to judge if the list has already contains the specific object of SeMo_WikiArticle.
Here is the code:
private void addPartial(List<SeMo_WikiArticle> allnewWiki, List<SeMo_WikiArticle> newWiki) {
for (SeMo_WikiArticle sw : newWiki) {
if (!allnewWiki.contains(sw)) {
allnewWiki.add(sw);
}
}
}

Unrecognized selector: [NSSQLToMany _setInverseManyToMany:]

This is the strangest error I've ever had, simply because I can't find any information on it anywhere.
Background:
I have an app using RestKit (current master) that maps to Core Data. I'm using a custom mapping provider (subclass of RKObjectMappingProvider). This generates all of the mappings that I need, similar to the RKGithub project.
Some of my objects have many-to-many relationships, so I have to register some of the relationships (in the mapping provider) after the others are set up to avoid an infinite recursion. (Friends has_many Friends has_many Friends...)
When the app runs and RestKit configures itself, an error occurs on this line (in RKManagedObjectStore.m)
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_managedObjectModel];
I can't step into the "initWithManagedObjectModel:" method. The only information I get is this exception in the logs:
-[NSSQLToMany _setInverseManyToMany:]: unrecognized selector sent to instance 0xcc78890
I have no idea what caused this or how to fix it. I can't find any documentation on it or even anyone who's had this problem before. All I could find was this dump of the iOS framework:
public struct NSSQLManyToMany : IEquatable<NSSQLManyToMany> {
internal NObjective.RuntimeObject Handle;
public static readonly RuntimeClass ClassHandle = CoreDataCachedClasses.NSSQLManyToMany;
public static implicit operator IntPtr( NSSQLManyToMany value ) {
return value.Handle;
}
public static implicit operator NObjective.RuntimeObject( NSSQLManyToMany value ) {
return value.Handle;
}
public override bool Equals( object value ) {
var compareTo = value as NSSQLManyToMany?;
return compareTo != null && Handle == compareTo.Value.Handle;
}
public bool Equals( NSSQLManyToMany value ) {
return Handle == value.Handle;
}
public static bool operator ==( NSSQLManyToMany value1, NSSQLManyToMany value2 ) {
return value1.Handle == value2.Handle;
}
public static bool operator !=( NSSQLManyToMany value1, NSSQLManyToMany value2 ) {
return value1.Handle != value2.Handle;
}
public NSSQLManyToMany( IntPtr value ) {
this.Handle = new RuntimeObject( value );
}
public static NSSQLManyToMany alloc() {
return new NSSQLManyToMany( ClassHandle.InvokeIntPtr( Selectors.alloc ) );
}
unsafe public NObjective.RuntimeObject inverseColumnName() {
RuntimeObject ___occuredException;
var ___result = NativeMethods.inverseColumnName( Handle, CachedSelectors.inverseColumnName, out ___occuredException, 0 );
if( ___occuredException != RuntimeObject.Null ) throw RuntimeException.Create( ___occuredException );
return new NObjective.RuntimeObject( ___result );
}
unsafe public NObjective.RuntimeObject inverseManyToMany() {
RuntimeObject ___occuredException;
var ___result = NativeMethods.inverseManyToMany( Handle, CachedSelectors.inverseManyToMany, out ___occuredException, 0 );
if( ___occuredException != RuntimeObject.Null ) throw RuntimeException.Create( ___occuredException );
return new NObjective.RuntimeObject( ___result );
}
unsafe public bool isMaster() {
RuntimeObject ___occuredException;
var ___result = NativeMethods.isMaster( Handle, CachedSelectors.isMaster, out ___occuredException, 0 );
if( ___occuredException != RuntimeObject.Null ) throw RuntimeException.Create( ___occuredException );
return ___result;
}
unsafe public bool isReflexive() {
RuntimeObject ___occuredException;
var ___result = NativeMethods.isReflexive( Handle, CachedSelectors.isReflexive, out ___occuredException, 0 );
if( ___occuredException != RuntimeObject.Null ) throw RuntimeException.Create( ___occuredException );
return ___result;
}
private static class NativeMethods {
[DllImport(Runtime.InteropLibrary, EntryPoint = "objc_msgSend_eh2")]
public static extern IntPtr inverseColumnName( RuntimeObject ___object, Selector ___selector, out RuntimeObject ___occuredException, int ___stackSize );
[DllImport(Runtime.InteropLibrary, EntryPoint = "objc_msgSend_eh2")]
public static extern IntPtr inverseManyToMany( RuntimeObject ___object, Selector ___selector, out RuntimeObject ___occuredException, int ___stackSize );
[DllImport(Runtime.InteropLibrary, EntryPoint = "objc_msgSend_eh2")]
public static extern bool isMaster( RuntimeObject ___object, Selector ___selector, out RuntimeObject ___occuredException, int ___stackSize );
[DllImport(Runtime.InteropLibrary, EntryPoint = "objc_msgSend_eh2")]
public static extern bool isReflexive( RuntimeObject ___object, Selector ___selector, out RuntimeObject ___occuredException, int ___stackSize );
}
static internal class CachedSelectors {
public static readonly Selector inverseColumnName = "inverseColumnName";
public static readonly Selector inverseManyToMany = "inverseManyToMany";
public static readonly Selector isMaster = "isMaster";
public static readonly Selector isReflexive = "isReflexive";
}
}
Which very clearly seems to have a setter:
public NSSQLManyToMany( IntPtr value ) {
this.Handle = new RuntimeObject( value );
}
Any ideas?
EDIT:
I should add that I've tried all of the "simple" solutions. Deleting the app from the sim doesn't work.
I suspect that it might be because I have an entity that has two "has and belongs to many" relationships with the same (different) entity. But I can't see why that would be an actual problem.
Just figured this out!
I had two relationships on one entity pointing to another entity, and they inadvertently had the same inverse.
To illustrate:
Part:
has many (Car*)cars, inverse parts
has one (Car*)deliveryTruck, inverse parts
A bit contrived, but the idea is there. I had to change the second parts to some other property.
Hopefully this will help someone else with the same cryptic error message. You'd expect clang to warn you about something like this! (It freaks out enough as it is if you don't have an inverse at all).

Mocking a static methods return called with in a Method being tested in groovy

I have a
class A {
public static boolean isRunning() {
if (ctx == null) { .. }
return ctx.isRunning();
}
}
I am testing a method that in the middle calls A.isRunning();
class B {
public void methodToBeTested() {
A.isRunning();
// do somthing
}
}
I want to test this in a way that when A.isRunning() is called it right away returns true and does not go initializing the context.
As class B does not have a property for type A, I am not sure what is the way to test this method?
Thanks
You can redefine your A.isRunning() through metaprogramming:
A.metaClass.static.isRunning = { true }
If you run that line before your test, it will make that method always return true

Duck type testing with C# 4 for dynamic objects

I'm wanting to have a simple duck typing example in C# using dynamic objects. It would seem to me, that a dynamic object should have HasValue/HasProperty/HasMethod methods with a single string parameter for the name of the value, property, or method you are looking for before trying to run against it. I'm trying to avoid try/catch blocks, and deeper reflection if possible. It just seems to be a common practice for duck typing in dynamic languages (JS, Ruby, Python etc.) that is to test for a property/method before trying to use it, then falling back to a default, or throwing a controlled exception. The example below is basically what I want to accomplish.
If the methods described above don't exist, does anyone have premade extension methods for dynamic that will do this?
Example: In JavaScript I can test for a method on an object fairly easily.
//JavaScript
function quack(duck) {
if (duck && typeof duck.quack === "function") {
return duck.quack();
}
return null; //nothing to return, not a duck
}
How would I do the same in C#?
//C# 4
dynamic Quack(dynamic duck)
{
//how do I test that the duck is not null,
//and has a quack method?
//if it doesn't quack, return null
}
If you have control over all of the object types that you will be using dynamically, another option would be to force them to inherit from a subclass of the DynamicObject class that is tailored to not fail when a method that does not exist is invoked:
A quick and dirty version would look like this:
public class DynamicAnimal : DynamicObject
{
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
bool success = base.TryInvokeMember(binder, args, out result);
// If the method didn't exist, ensure the result is null
if (!success) result = null;
// Always return true to avoid Exceptions being raised
return true;
}
}
You could then do the following:
public class Duck : DynamicAnimal
{
public string Quack()
{
return "QUACK!";
}
}
public class Cow : DynamicAnimal
{
public string Moo()
{
return "Mooooo!";
}
}
class Program
{
static void Main(string[] args)
{
var duck = new Duck();
var cow = new Cow();
Console.WriteLine("Can a duck quack?");
Console.WriteLine(DoQuack(duck));
Console.WriteLine("Can a cow quack?");
Console.WriteLine(DoQuack(cow));
Console.ReadKey();
}
public static string DoQuack(dynamic animal)
{
string result = animal.Quack();
return result ?? "... silence ...";
}
}
And your output would be:
Can a duck quack?
QUACK!
Can a cow quack?
... silence ...
Edit: I should note that this is the tip of the iceberg if you are able to use this approach and build on DynamicObject. You could write methods like bool HasMember(string memberName) if you so desired.
Try this:
using System.Linq;
using System.Reflection;
//...
public dynamic Quack(dynamic duck, int i)
{
Object obj = duck as Object;
if (duck != null)
{
//check if object has method Quack()
MethodInfo method = obj.GetType().GetMethods().
FirstOrDefault(x => x.Name == "Quack");
//if yes
if (method != null)
{
//invoke and return value
return method.Invoke((object)duck, null);
}
}
return null;
}
Or this (uses only dynamic):
public static dynamic Quack(dynamic duck)
{
try
{
//invoke and return value
return duck.Quack();
}
//thrown if method call failed
catch (RuntimeBinderException)
{
return null;
}
}
Implementation of the HasProperty method for every IDynamicMetaObjectProvider WITHOUT throwing RuntimeBinderException.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using Microsoft.CSharp.RuntimeBinder;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
namespace DynamicCheckPropertyExistence
{
class Program
{
static void Main(string[] args)
{
dynamic testDynamicObject = new ExpandoObject();
testDynamicObject.Name = "Testovaci vlastnost";
Console.WriteLine(HasProperty(testDynamicObject, "Name"));
Console.WriteLine(HasProperty(testDynamicObject, "Id"));
Console.ReadLine();
}
private static bool HasProperty(IDynamicMetaObjectProvider dynamicProvider, string name)
{
var defaultBinder = Binder.GetMember(CSharpBinderFlags.None, name, typeof(Program),
new[]
{
CSharpArgumentInfo.Create(
CSharpArgumentInfoFlags.None, null)
}) as GetMemberBinder;
var callSite = CallSite<Func<CallSite, object, object>>.Create(new NoThrowGetBinderMember(name, false, defaultBinder));
var result = callSite.Target(callSite, dynamicProvider);
if (Object.ReferenceEquals(result, NoThrowExpressionVisitor.DUMMY_RESULT))
{
return false;
}
return true;
}
}
class NoThrowGetBinderMember : GetMemberBinder
{
private GetMemberBinder m_innerBinder;
public NoThrowGetBinderMember(string name, bool ignoreCase, GetMemberBinder innerBinder) : base(name, ignoreCase)
{
m_innerBinder = innerBinder;
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
var retMetaObject = m_innerBinder.Bind(target, new DynamicMetaObject[] {});
var noThrowVisitor = new NoThrowExpressionVisitor();
var resultExpression = noThrowVisitor.Visit(retMetaObject.Expression);
var finalMetaObject = new DynamicMetaObject(resultExpression, retMetaObject.Restrictions);
return finalMetaObject;
}
}
class NoThrowExpressionVisitor : ExpressionVisitor
{
public static readonly object DUMMY_RESULT = new DummyBindingResult();
public NoThrowExpressionVisitor()
{
}
protected override Expression VisitConditional(ConditionalExpression node)
{
if (node.IfFalse.NodeType != ExpressionType.Throw)
{
return base.VisitConditional(node);
}
Expression<Func<Object>> dummyFalseResult = () => DUMMY_RESULT;
var invokeDummyFalseResult = Expression.Invoke(dummyFalseResult, null);
return Expression.Condition(node.Test, node.IfTrue, invokeDummyFalseResult);
}
private class DummyBindingResult {}
}
}
impromptu-interface seems to be a nice Interface mapper for dynamic objects... It's a bit more work than I was hoping for, but seems to be the cleanest implementation of the examples presented... Keeping Simon's answer as correct, since it is still the closest to what I wanted, but the Impromptu interface methods are really nice.
The shortest path would be to invoke it, and handle the exception if the method does not exist. I come from Python where such method is common in duck-typing, but I don't know if it is widely used in C#4...
I haven't tested myself since I don't have VC 2010 on my machine
dynamic Quack(dynamic duck)
{
try
{
return duck.Quack();
}
catch (RuntimeBinderException)
{ return null; }
}
Have not see a correct answer here, MS provides an example now with casting to a dictionary
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
foreach (var property in (IDictionary<String, Object>)employee)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33