Is it possible to create/design in a way to privately set a property but only expose the ability to get the properties to the consumers?
I've tackled a multiple inheritance property by making the base class wrapper a member of the concrete classes wrapper. I'd rather not allow someone to write over the base classes instance in the set of it's own property. But I can't seem to exclude set and set the base property and I can't make the set private.
Any ideas?
Code:
ConcreteClassWrapper(); // here I want to setup base class, i.e. give it a pointer to the actual C++ model I'm working with.
property BaseClassWrapper^ BaseClass
{
BaseClassWrapper^ get() { return baseClass; }
// I want to avoid giving my consumers the ability to set this property.
void set(BaseClassWrapper^ value) { baseClass= value; }
}
private:
BaseClassWrapper^ baseClass; // Having a base class wrapper makes it easier on code writing.. i.e. I don't need to implement interfaces. I just want to use my C++ code in C# Microsoft GOD!!!
EDIT:
I'm an idiot, I can access the private member...
This is just one answer... Still want to know why private setters arent' a thing
I just have to access my private member of my ConcreteClassWrapper and set the base class there. Then I can remove the set in the BaseClassWrapper property.
Did you try this :
property BaseClassWrapper^ BaseClass
{
BaseClassWrapper^ get() { return baseClass; }
private:
void set(BaseClassWrapper^ value) { baseClass= value; }
}
This is the way you write a private setter in a property. In the case of C++/CX, the property keyword is just a new keyword to allow C++/CX compiler to generate some C++ code, so the syntax for things like private, public, protected is the same.
Related
We are using Groovy and Guice on a project and I came across the following error:
groovy.lang.MissingPropertyException: No such property: myService for class: com.me.api.services.SomeService$$EnhancerByGuice$$536bdaec
Took a bit to figure out, but it was because I was referencing a private class member, that was injected, inside of a closure. Can anyone shed any light as to why this happens?
Furthermore, is there any better way of doing this?
Here is a snippet of what the class looks like:
import javax.inject.Inject
import javax.inject.Singleton
#Singleton
class MyService extends BaseService<Thing> {
#Inject
private ThingDao thingDao
#Inject
private OtherService<Thing> otherService
#Override
List<Thing> findAll() {
List<Thing> things = this.dao.findAll()
things.each {
//Note: This doesn't work!
otherService.doSomething()
}
things
}
I either have to use a standard for loop or not use the injected member which then tends to lead to code duplication.
TLDR;
Either declare otherService public (remove private modifier) or add a getter OtherService<Thing> getOtherService(){otherService}
If you absolutely want to avoid exposing the field through a property, you can do the following trick: create a local variable outside the Closure scope that references your service:
OtherService<Thing> otherService=this.otherService
things.each {
//Note: This will work! Because now there is a local variable in the scope.
//This is handled by normal anonymous inner class mechanisms in the JVM.
otherService.doSomething()
}
Explanation
Under the hood, your closure is an object of an anonymous class, not the object that has your private field, otherService.
This means that it can't resolve a direct reference to the field. Accessing a symbol inside the closure will first look at local variables, and if no match is found, the getProperty() method in Closure will be called to find a property, depending on the resolution strategy that you defined. By default, this is OWNER_FIRST.
If you look the code of Closure#getProperty:
switch(resolveStrategy) {
case DELEGATE_FIRST:
return getPropertyDelegateFirst(property);
case DELEGATE_ONLY:
return InvokerHelper.getProperty(this.delegate, property);
case OWNER_ONLY:
return InvokerHelper.getProperty(this.owner, property);
case TO_SELF:
return super.getProperty(property);
default:
return getPropertyOwnerFirst(property);
}
You see that the owner, delegate and declaring objects need to have matching properties.
In groovy, if you declare a field private, you won't get auto-generated accessor methods, so no properties will be publicly exposed for outside objects.
I have a problem and I searched a solution about it. Lucky, I red lot of post about it but I'm lost with the explaination I found. The initale problem is coming from a personal project about the polyline of the Xamarin.Forms.Map where the initialization is realized by a binding from the XAML part..
Let me be clear by an example :
I have an object CustomMap.cs which inherit from Xamarin.Forms.Map (This file is in the PCL part -> CustomControl/CustomMap.cs)
public class CustomMap : Map, INotifyPropertyChanged
{
public static readonly BindableProperty PolylineAddressPointsProperty =
BindableProperty.Create(nameof(PolylineAddressPoints), typeof(List<string>), typeof(CustomMap), null);
public List<string> PolylineAddressPoints
{
get { return (List<string>)GetValue(PolylineAddressPointsProperty); }
set
{
SetValue(PolylineAddressPointsProperty, value);
this.GeneratePolylineCoordinatesInner();
}
}
// ...
}
So the Xaml part of the page, where the control is called, looks like that:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:control="clr-namespace:MapPolylineProject.CustomControl;assembly=MapPolylineProject"
x:Class="MapPolylineProject.Page.MainPage">
<ContentPage.Content>
<control:CustomMap x:Name="MapTest" PolylineAddressPoints="{Binding AddressPointList}"
VerticalOptions="Fill" HorizontalOptions="Fill"/>
</ContentPage.Content>
</ContentPage>
The Csharp part:
public partial class MainPage : ContentPage
{
public List<string> AddressPointList { get; set; }
public MainPage()
{
base.BindingContext = this;
AddressPointList = new List<string>()
{
"72230 Ruaudin, France",
"72100 Le Mans, France",
"77500 Chelles, France"
};
InitializeComponent();
//MapTest.PolylineAddressPoints = AddressPointList;
}
}
So, everything is fine if I edit the PolylineAddressPoints from the object instance (if the commented part isnt' commented..), but if I init the value from the XAML (from the InitializeComponent();), it doesn't work, the SetValue, in the Set {}, isn't called..
I then searched on the web about it and get something about the Dependency Properties? or something like that. So I tried some solutions but, from WPF, so some methods, such as DependencyProperty.Register();. So yeah, I can't find the way to solve my problem..
I also though about something, if DependencyProperty.Register(); would exists in Xamarin.Forms, then it means I would have to do it for each values? Because, if every value has to be set by a XAML binding logic, it would not work, I would have to register every value, doesn't it?
I'm sorry if I'm not clear, but I'm so lost about this problem.. Please, do not hesitate to ask for more details, thank in advance !
I finaly got a solution just over here => Ignore the Binding initialization
Copy paste from Stackoverflow. This following answer was given by Stephane Delcroix, thank to him !
There are multiple questions in this:
Why is the property setter never called when using Xaml ?
Am I properly defining my BindableProperty ?
Why is my binding failing ?
Let me answer them in a different order.
Am I properly defining my BindableProperty ?
The BindableProperty declaration is right, but could be improved by using an IList<string>:
public static readonly BindableProperty PolylineAddressPointsProperty =
BindableProperty.Create(nameof(PolylineAddressPoints), typeof(IList<string>), typeof(CustomMap), null);
but the property accessor is wrong, and should only contains this:
public IList<string> PolylineAddressPoints
{
get { return (IList<string>)GetValue(PolylineAddressPointsProperty); }
set { SetValue(PolylineAddressPointsProperty, value); }
}
I'll tell you why while answering the next question. But you want to invoke a method when the property has changed. In order to do that, you have to reference a propertyChanged delegate to CreateBindableProperty, like this:
public static readonly BindableProperty PolylineAddressPointsProperty =
BindableProperty.Create(nameof(PolylineAddressPoints), typeof(IList<string>), typeof(CustomMap), null,
propertyChanged: OnPolyLineAddressPointsPropertyChanged);
And you have to declare that method too:
static void OnPolyLineAddressPointsPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
((CustomMap)bindable).OnPolyLineAddressPointsPropertyChanged((IList<string>)oldValue, (IList<string>)newValue);
}
void OnPolyLineAddressPointsPropertyChanged(IList<string> oldValue, IList<string> newValue)
{
GeneratePolylineCoordinatesInner();
}
Why is the property setter never called when using Xaml ?
The property, and the property accessors, are only meant to be invoked when accessing the property by code. C# code.
When setting a property with a BindablePrperty backing store from Xaml, the property accessors are bypassed and SetValue() is used directly.
When defining a Binding, both from code or from Xaml, property accessors are again bypassed and SetValue() is used when the property needs to be modified. And when SetValue() is invoked, the propertyChanged delegate is executed after the property has changed (to be complete here, propertyChanging is invoked before the property change).
You might wonder why bother defining the property if the bindable property is only used by xaml, or used in the context of Binding. Well, I said the property accessors weren't invoked, but they are used in the context of Xaml and XamlC:
a [TypeConverter] attribute can be defined on the property, and will be used
with XamlC on, the property signature can be used to infer, at compile time, the Type of the BindableProperty.
So it's a good habit to always declare property accessors for public BindableProperties. ALWAYS.
Why is my binding failing ?
As you're using CustomMap as bot View and ViewModel (I won't tell the Mvvm Police), doing this in your constructor should be enough:
BindingContext = this; //no need to prefix it with base.
As you're doing it already, your Binding should work once you've modified the BindableProperty declaration in the way I explained earlier.
I want to create a code in C# for Private constructor.
I want that it should allow only one object to be created but when I try to create more than one a message showing no more object can be created should be shown.
I don't want to use static constructor in this code.
How do I do that in C#?
You may use static counter or flag that will be set in your private counstructor to show that at least one instance were created.
But first of all, I suggest you to pay attention to Singleton pattern.
Simple, this is the classic singleton pattern:
public class MyClass
{
public static MyClass Instance;
private MyClass()
{
if (Instance != null)
throw new InvalidOperationException("no more object can be created");
// do other constructor logic
Instance = this;
}
}
Please note that synchronization has been left out. This code need synchronization for thread safe purpose.
Properties in groovy seem like class fields in java without an access modifier. Is that true? Or they have a special meaning. It seems like there is no way to make the properties private?
When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.
class A {
String property
/*
private String property
public void setProperty(String property) { ... }
public String getProperty() { ... }
*/
}
If we declare a public instance variable field we just get a public field, without a setter/getter method pair.
class A {
public String field
/*
public String field
*/
}
From a Groovy client's pov, there is no difference between accessing a Groovy property and a public field at runtime
def a = new A()
println a.field
println a.property
although a.field accesses the instance variable directly and a.property actually calls a.getProperty() (or a.setProperty(...) when assigning a value). But as the property complies to the JavaBeans spec, the class can seamlessly be used in Java-based environments.
I do not see much sense in making a "private property". private restricts the use of a method or instance/class variable to the hosting class type. But maybe you were referring to making a private field instance variable.
Properties can normally be treated like fields, but they are actually backed by implicit getters/setters, so you can still reference them like fields or set them equal to values. Behind the scenes, they are using getters/setters (which you can redefine if you care to).
This page has details on properties/fields and access modifiers (see especially the "Property and field rules" section): https://groovy-lang.org/objectorientation.html#_fields_and_properties
It also shows that you can make a private property (private field backed by private getters/setters), but you have to be explicit in defining the getters/setters.
Example: I would like to have a template that inserts a method. If the class is declared sealed, then I'd like the method to be declared private. If the class is not sealed, then I'd like the method to be declared protected virtual.
Another example. If the class is inherited, and the superclass contains a method X, then call base.X(); otherwise do nothing.
Is this type of conditional processing available in ReSharper? I guess this is getting close to T4 territory but it would be really handy to be able to do this in Live Templates.
In case it matters, I'm using R# 7.
Detailed scenario
Both of these requirements came from trying to write a Live Template for the IDisposable pattern (see Implementing the Disposable Pattern Correctly). The generated code needs to be different depending on whether the class is a base class or subclass. One can define two templates, but it is not difficult to dream up other scenarios where this would be useful. Here's the code in my IDisposable template:
#region IDisposable Pattern
/// <summary>
/// Finalizes this instance (called prior to garbage collection by the CLR)
/// </summary>
~$ClassName$() {
Dispose(fromUserCode: false);
}
public void Dispose()
{
Dispose(fromUserCode: true);
GC.SuppressFinalize(this);
}
private bool disposed = false;
// Declare as private if this class is sealed.
protected virtual void Dispose(bool fromUserCode)
{
if (!disposed)
{
if (fromUserCode)
{
// ToDo - Dispose managed resources (call Dispose() on any owned objects).
// Do not dispose of any objects that may be referenced elsewhere.
}
// ToDo - Release unmanaged resources here, if necessary.
}
disposed = true;
// ToDo: Call the base class's Dispose(Boolean) method, if available.
// base.Dispose(fromUserCode);
}
#endregion
You can certainly do this. What you need is a plugin that implements the corresponding live template macro that performs the actual check.